我有模型“付款”,“预估”和“报价”,付款具有多态关系,它可以属于报价或预估,同时报价可以有多个预估,因此预估始终属于报价。
基本上,所有付款总是属于一个报价,有时是直接的,有时是通过预估的:
quotes:
id
estimates:
id
quote_id
payments:
id
paymentable_id
paymentable_type ("App\Models\Quote" or "App\Models\Estimate")我的问题是,我如何定义这些关系,以便在使用$quote->payments时,它不仅会返回与报价直接相关的付款,还会返回与属于该报价的预估相关的付款。
有什么建议吗?提前谢谢。
发布于 2020-12-14 00:07:13
是的,这是可能的,你可以尝试一些类似于bellow的东西:
定义三种关系:
首先是直接支付,方式如下:
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());
}https://stackoverflow.com/questions/65271370
复制相似问题