6

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();
dev21
  • 520
  • 2
  • 8
  • 22

2 Answers2

1

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.

D Malan
  • 10,272
  • 3
  • 25
  • 50
-1

You pass local scope parameters to closure functions using use

... ->with(
        ['response_pricings' => function ($query) use ($_user_id) {
            $query->where('user_id', $_user_id);
         }
        ]
      )
      ->where(....

More info in this Q&A: In PHP 5.3.0, what is the function "use" identifier?

Amarnasan
  • 14,939
  • 5
  • 33
  • 37