Home > Backend Development > PHP Tutorial > How to Select Specific Columns from Related Models in Laravel Eloquent using `with()`?

How to Select Specific Columns from Related Models in Laravel Eloquent using `with()`?

Linda Hamilton
Release: 2024-12-16 21:50:14
Original
276 people have browsed it

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template