0

I have 3 tables

Users Table

+----+-------+----------+
| id | email | password |
+----+-------+----------+
| 1  | 1     | John     |
+----+-------+----------+

user_details Table

+----+--------------------+------------+-----------+
| id | user_id [FK_users] | first_name | last_name |
+----+--------------------+------------+-----------+
| 1  | 1                  | John       | Kevin     |
+----+--------------------+------------+-----------+

Posts Table

+----+--------------------+----------+
| id | user_id [FK_users] | title    |
+----+--------------------+----------+
| 1  | 1                  | 1st Post |
+----+--------------------+----------+

Now i already created all the relationships in the models and now i can access the user_details table by below eloquent query it returns whole users table and user_details table but i only want to select first_name and last_name from user_details table how do i do that?

$posts= Post::with('city:id,name_en', 'user.userDetail')->where('id', $id)->get();
Ahamed
  • 29
  • 2
  • 10

1 Answers1

1

this will fetch all the 'post' attributes, 'user' id, 'user_details' user_id, first_name, last_name

$posts= Post::with([
    'city:id,name_en',
    'user' => function ($query) {
        $query->select('id');
    },
    'user.userDetail' => function($query) {
        $query->select(['user_id', 'first_name', 'last_name']);
    }
])->where('id', $id)->get();
Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28
  • How to fetch only few attributes from "Post" in this case or set alias for few of columns in Post ? – Brainy Prb May 24 '20 at 17:12
  • fetch only few attributes: `Post::with(bla bla bla)->select([field_name1, field_name2])->where(bla bla bla);`. Don't forget to includes required foreign keys when selecting. – Tharaka Dilshan May 25 '20 at 15:07