mardi 30 avril 2019

Getting a value from a relationship within a relationship in Laravel 5.8

So I have a approved_quote relationship on my jobs Model.

public function approved_quote()
{
    return $this->hasOne(JobQuote::class, 'job_id')->whereNotNull('approved_at');
}

I want to pull back the products that have been quoted. I have tried a couple of methods however both have unexpected results.

Attempt 1

public function quoted_job_products()
{
    return $this->hasMany(JobProduct::class, 'job_id')->where('job_quote_id', $this->approved_quote()->first()->id ?? 0);
}

However $this->approved_quote->get(); pulls back 14 records that are not really relevant (or right) and so ->first() just pulls back the first of that which is wrong.

Attempt 2

public function quoted_job_products()
{
    return $this->hasMany(JobProduct::class, 'job_id')->where('job_quote_id', $this->approved_quote->id ?? 0);
}

$this->approved_quote returns null and so it does not work.

Any suggestions as to how this can be achieved? (Preferably without having a approved_quote_id on jobs however I will if I need to).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire