To include an alias in Laravel's eager loading for a select query, you can use the selectRaw
method:
$users = User::with(['posts' => function($query) {
$query->select('title as post_title', 'content');
}])->selectRaw('id, name as user_name')->get();
In this example, we are eager loading the posts
relationship for User
model, but we only want to select the title
column from posts
table as post_title
. We use the selectRaw
method to select the id
and name
column from users
table while also using an alias for name
as user_name
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-29 08:23:22 +0000
Seen: 11 times
Last updated: May 29 '23
How can Laravel Scout (Meilisearch driver) be utilized for intricate relational searches?
What does the message "419 (unknown status)" mean in relation to Laravel Stripe checkout?
What is the procedure for testing scheduling in Laravel?
What is the distinction between terminable middleware and after middleware in Laravel?
In Laravel, what is the process for comparing two objects and obtaining distinct columns?
How can I get a record of all the files in a public folder in Laravel?
How to change a string to a date format in Laravel?
What is the process of bringing in multiple rows from an excel sheet in Laravel?