How to add alias in laravel eager loading to select query

✔ Recommended Answer

The query doesn't know which id 'id as optionId' should be on since questionBankOptions apparently uses an inner join. You'll need to specify the table name. I'm going to guess that you want the id from question_bank_options, so just add in it like below.

$q->select('question_bank_options.id as optionId','question_bank_id',...

Source: stackoverflow.com

Answered By: aynber

Method #2

In Laravel, you can use the select() method along with aliases in eager loading to select specific columns from a related table with custom names.

Here's an example:

php
$users = User::with(['posts' => function ($query) { $query->select('user_id', 'title AS post_title'); }])->get();

In this example, we're eager loading the posts relationship on the User model, and using the select() method to select only the user_id and title columns from the posts table. We also use the AS keyword to give the title column an alias of post_title.

Now, when we access the posts relationship on a User model instance, we'll only have access to the user_id and post_title columns, like this:

php
foreach ($users as $user) { foreach ($user->posts as $post) { echo $post->user_id; echo $post->post_title; } }

Note that the eager loaded relationship will still contain all of the columns from the posts table, but when accessing the relationship on a User model instance, only the selected columns (and aliases) will be available.

Also note that you can use any valid SQL expression in the select() method, including aggregate functions, subqueries, and more.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755