Back

Constraining Eager Loads with column from parent Model


Hello Everyone,

I am looking for something like this

/**
 * Get offer related to the request.
 */
public function offer()
{
    return $this->hasOne('App\Offer', 'request_id', 'id')->where('boss_id', 'requests.boss_id');
}

If you can look at the code I want to put constrains on the relationship here so that it only gets the offer that has the same boss_id as the boss_id in the model which this realtionship is defined. in my cas this relationship is defined in the Request model.

Mubassir Hayat replied 1 week ago

I have done this

/**
 * Get offer related to the request.
 */
public function offer()
{
    return $this->hasOne('App\Offer', 'request_id', 'id')->where('boss_id', $this->boss_id);
}

and

/**
 * Get offer related to the request.
 */
public function offer()
{
    return $this->hasOne('App\Offer', 'request_id', 'id')->where('boss_id', $this->getAttribute('boss_id'));
}

but had no luck.

If I need to implement something I can do that as well but I need someone to put me in the right direction.

Firtzberg replied 1 week ago

Hi Sir Mubassir,

are you telling me

return $this->hasOne('App\Offer', 'request_id', 'id')->where('boss_id', $this->boss_id);

gives you an Offer with boss_id different from the Request 's boss_id ?

The only way I can image this happening is that you have a Request with a loaded Offer, e.g. somewhere in your code you call

$request->offer;

and after that change the boss_id of the Request . The Offer will remain unchanged and when you invoke

$request->offer;

afterwards you will get the same Offer . The database will not be queried again.

Could this be your use case?

Ask yourself why do you have boss_id in the Offer when you already have it in the Request to which it belongs.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us