Reputation: 29
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();
Upvotes: 0
Views: 4878
Reputation: 4499
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();
Upvotes: 1