Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent ->with() and ->select() conflict with each other

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 ?

like image 824
user3702861 Avatar asked Oct 18 '25 00:10

user3702861


1 Answers

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.

like image 51
lagbox Avatar answered Oct 19 '25 17:10

lagbox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!