Get Specific Columns Using “With()” Function in Laravel Eloquent

后端 未结 13 2296
清酒与你
清酒与你 2020-11-22 16:57

I have two tables, User and Post. One User can have many posts and one post belongs to only one user

13条回答
  •  臣服心动
    2020-11-22 17:34

    I came across this issue but with a second layer of related objects. @Awais Qarni's answer holds up with the inclusion of the appropriate foreign key in the nested select statement. Just as an id is required in the first nested select statement to reference the related model, the foreign key is required to reference the second degree of related models; in this example the Company model.

    Post::with(['user' => function ($query) {
            $query->select('id','company_id', 'username');
        }, 'user.company' => function ($query) {
            $query->select('id', 'name');
        }])->get();
    

    Additionally, if you want to select specific columns from the Post model you would need to include the user_id column in the select statement in order to reference it.

    Post::with(['user' => function ($query) {
            $query->select('id', 'username');
        }])
        ->select('title', 'content', 'user_id')
        ->get();
    

提交回复
热议问题