是否可以通过 Laravel 模型中的不同路径(中间模型)定义多态关系?
Is it possible to define a polymorphic relationship through different paths (intermediate model) in Laravel models?
我有模型“付款”、“估算”和“报价”,付款具有多态关系,它可以属于报价或估算,同时报价可以有多个估算,因此估计总是属于报价。
基本上,所有付款总是属于报价,有时是直接的,有时是通过估算:
quotes:
id
estimates:
id
quote_id
payments:
id
paymentable_id
paymentable_type ("App\Models\Quote" or "App\Models\Estimate")
我的问题是,我如何定义关系,以便在我使用 $quote->payments
时,它不仅会 return 与报价直接相关的付款,还会与相关的付款属于该报价的估计。
有什么建议吗?提前致谢。
是的,这是可能的,您可以尝试以下方法:
定义三种关系:
首先直接付款如下:
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());
}
我有模型“付款”、“估算”和“报价”,付款具有多态关系,它可以属于报价或估算,同时报价可以有多个估算,因此估计总是属于报价。
基本上,所有付款总是属于报价,有时是直接的,有时是通过估算:
quotes:
id
estimates:
id
quote_id
payments:
id
paymentable_id
paymentable_type ("App\Models\Quote" or "App\Models\Estimate")
我的问题是,我如何定义关系,以便在我使用 $quote->payments
时,它不仅会 return 与报价直接相关的付款,还会与相关的付款属于该报价的估计。
有什么建议吗?提前致谢。
是的,这是可能的,您可以尝试以下方法:
定义三种关系:
首先直接付款如下:
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());
}