Reputation: 757
Consider this code:
Articles
::select('article_id', 'article_text') //This one does not work as expected
->with([
'user' => function($q){
$q->select('user_id', 'user_name'); // This one works fine
}
])
->get();
When building query in Eloquent, we can use ->with() to retreive associated models. We can also attach ->select(), to determine which columns should be selected from associated model. However, looks like we loose possibility to specify which columns should be selected from the base model we are querying.
In this example, because of the first ::select
, the final results returned do not include user
, because it's not included in the ::select
list. If I include it there, then it throws an error about column not found
. Eloquent is not smart enough to understand that I mean relationship, not column.
Is it possible to specify which columns should be returned from user
as well as from article
?
Upvotes: 4
Views: 3568
Reputation: 50561
You can select the columns you want with eager loading constraints but you still need to at the least select the columns that are used for the relationship.
Random example:
User::with(['tickets' => function ($q) {
$q->select('user_id');
}])->select('id')->get();
Those are the minimum fields needed for that to return results for the relationship and have them attached to the correct models.
You would need to select a minimum of user_id
from tickets
and id
from users
. Those are the columns used for this relationship. tickets.user_id
-> users.id
Query Log:
'select `id` from `users`'
'select `user_id` from `tickets` where `tickets`.`user_id` in ( .... )'
Having those fields gives you what you need for the relationship to return results, now you can add additional fields to those selects.
I hope that helps.
Upvotes: 4