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

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

    You can do it like this since Laravel 5.5:

    Post::with('user:id,username')->get();
    

    Care for the id field and foreign keys as stated in the docs:

    When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.

    For example, if the user belongs to a team and has a team_id as a foreign key column, then $post->user->team is empty if you don't specifiy team_id

    Post::with('user:id,username,team_id')->get();
    

提交回复
热议问题