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

故事扮演 提交于 2019-12-24 04:29:06

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/27702492/laravel-eloquent-with-and-select-conflict-with-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!