phplaraveleloquenthas-many-througheager-loading

How to add alias in laravel eager loading to select query


I want to optimize my code so I am trying to select only those fields which I actually require into questionBankOptionspart but the issue is I am getting the error of Integrity constraint violation: 1052 Column 'id' in field list is ambiguous so tried to remove this part select('id as optionId','question_bank_id','option','option_image','correct','status') which is there in questionBankOptions and I didnot see any error. So I cant understand why I am getting this error.


$assesmentQuestion = AssesmentQuestion::with([
            'questionBank:id,remarks,question,question_img,question_format',
            'questionCategories',
            'questionBankOptions' => function($q) {
                $q->select('question_bank_options.id as optionId','question_bank_id','option','option_image','correct','status')
                  ->where('status',0);
            }
        ])
        ->select(['id','question_bank_id','preferences','assesment_id'])
        ->where('assesment_id',$id)
        ->orderBy('preferences','ASC')
        ->get();

Solution

  • 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',...