Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parent column value in subquery in eloquent

How to pass _user_id column value inside with in $query. this is hasMany relationship. I am not able to figure out how to user user_id of RFX into the $query where condition.

public function response_pricings(){
    return $this->hasMany('App\Models\Website\RFXRequestPricingResponse', ['rfx_request_id'=>'_rfx_request_id', 'user_id'=>'_user_id'])->selectRaw("*");
}

return RFXRequestSupplierResponded::select(
    'id as _id',
    'rfx_request_id as _rfx_request_id',
    'user_id as _user_id',
    'status',
    'is_qualified',
    DB::RAW('(SELECT name FROM users WHERE id=user_id) as user_name'),
    DB::RAW('(SELECT note FROM rfx_request_response_notes WHERE rfx_request_id='.$rfx_request_id.' AND user_id=rfx_request_suppliers_responded.user_id LIMIT 1) as note')
)
->with(
    [
        'response_pricings' => function ($query) {
            /*$query->where('user_id', $_user_id);*/
        }
    ]
)
->where('rfx_request_id',$rfx_request_id)
->get();
like image 853
dev21 Avatar asked Jan 18 '18 11:01

dev21


1 Answers

When you have defined a relationship on a model, Laravel would automatically link the models using either the dynamically determined foreign keys or foreign keys that you have specified. Therefore you don't need to pass in the user_id to the query. Laravel would automatically use the the user_id of the RFXRequestSupplierResponded instance.

However, it looks like you are linking the RFXRequestSupplierResponded to the RFXRequestPricingResponse model using multiple foreign keys. Eloquent doesn't have built-in support for that. Take a look at the answers to this question for examples on how to add support for multiple foreign keys.

like image 103
D Malan Avatar answered Nov 11 '22 12:11

D Malan