1

我有“付款”、“估计”和“报价”模型,付款具有多态关系,它可以属于报价或估计,同时报价可以有许多估计,所以估计总是会属于一个报价。

基本上,所有付款总是属于报价,有时直接,有时通过估算:

quotes:
    id 

estimates:
    id
    quote_id 

payments:
    id 
    paymentable_id 
    paymentable_type ("App\Models\Quote" or "App\Models\Estimate")

我的问题是,如何定义关系,所以当我使用 时$quote->payments,它不仅会返回与报价直接相关的付款,还会返回与属于该报价的估计相关的付款。

有什么建议么?提前致谢。

4

1 回答 1

0

是的,有可能,您可以尝试以下方法:

定义三种关系:

首先直接付款如下:

public function directPayments(){
    return $this->morphMany(Payment::class,"paymentable");
}

另一个使用 hasManyThrough 检索间接:

/**
* returns models, not relation 
*/
public function indirectPayments(){
    return  $this->hasManyThrough(
                                    Payment::class,
                                    Estimate::class,
                                    'quote_id',
                                    'paymentable_id',
                                    'id',
                                    'id')
                  ->where('paymentable_type',"App\Models\Estimate");
}

你可以有一个函数来聚合它们

public function getPaymentsAttribute(){
//merge or union in collections
    return $this->directPayments->union($this->indirectPayments()->get());
}
于 2020-12-13T16:07:13.320 回答