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

后端 未结 13 2159
清酒与你
清酒与你 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:47

    Well I found the solution. It can be done one by passing a closure function in with() as second index of array like

        Post::with(array('user'=>function($query){
            $query->select('id','username');
        }))->get();
    

    It will only select id and username from other table. I hope this will help others.


    Remember that the primary key (id in this case) needs to be the first param in the $query->select() to actually retrieve the necessary results.*

提交回复
热议问题