从Laravel 5.8中关系中的关系中获取值

从Laravel 5.8中关系中的关系中获取值,laravel,laravel-5,relationship,Laravel,Laravel 5,Relationship,因此,我在我的工作模型上有一个批准的关系 public function approved_quote() { return $this->hasOne(JobQuote::class, 'job_id')->whereNotNull('approved_at'); } 我想收回已报价的产品。我尝试了几种方法,但都有意想不到的结果 尝试1 public function quoted_job_products() { return $this->hasMany

因此,我在我的
工作
模型上有一个
批准的关系

public function approved_quote()
{
    return $this->hasOne(JobQuote::class, 'job_id')->whereNotNull('approved_at');
}
我想收回已报价的产品。我尝试了几种方法,但都有意想不到的结果

尝试1

public function quoted_job_products()
{
    return $this->hasMany(JobProduct::class, 'job_id')->where('job_quote_id', $this->approved_quote()->first()->id ?? 0);
}
但是
$this->approved_quote->get()
回调14条不相关(或不正确)的记录,因此
->first()
只回调第一条错误的记录

尝试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
返回null,因此它不起作用


关于如何实现这一点,有什么建议吗?(最好没有
批准的
作业id
,但是如果需要,我会这样做)。

将该查询拆分为较小的部分如何?这不是一个完整的解决方案,但可能会有所帮助。我不确定我的关系是否正确

模型
  • 工作
  • 工作产品
  • 工作报价
关系
  • Job有一个JobProduct
  • 工作有很多工作
  • JobQuote属于JobProduct
解决方案 及


沃迪,你能和我们分享一下工作、报价和产品之间的关系吗?工作有很多报价。作业有一个接受的报价(带有接受的报价)。报价有产品。你能分享模型关系吗?这样我可以帮你吗?
$this->approvedJobQuote()->jobProduct()
这是错误的。您不能在
查询生成器
实例上调用Realationship。它不是在查询生成器上调用它,而是在上一步中first()返回的JobQuote实例上调用它
class Job extends Model {
    public function jobQuotes()
    {
        return $this->hasMany(JobQuote::class);
    }

    public function approvedJobQuote()
    {
        return $this->jobQuotes()->whereNotNull('approved_at')->first()
    }

    public function approvedJobProduct()
    {
        return $this->approvedJobQuote()->jobProduct()
    }
}
class JobQuote extends Model {
    public function jobProduct()
    {
        return $this->belongsTo(JobProduct::class);
    }
}