Home >Backend Development >PHP Tutorial >How to Select Specific Columns from Related Models in Laravel Eloquent using `with()`?
Retrieve Specific Columns with Laravel Eloquent's "With()" Function
Getting specific columns from related models using Laravel Eloquent's "with()" function can be achieved by passing a second index to the "with()" array as a closure function:
Post::query() ->with(['user' => function ($query) { $query->select('id', 'username'); }]) ->get();
This code will retrieve all columns from the "posts" table and only the "id" and "username" columns from the related "users" table.
Primary Key Limitation
It's important to note that when using this approach, the primary key of the related table (in this case, "id") is required as the first parameter in the "$query->select()" function. This ensures that the necessary results are retrieved.
The above is the detailed content of How to Select Specific Columns from Related Models in Laravel Eloquent using `with()`?. For more information, please follow other related articles on the PHP Chinese website!