Php 在Laravel模型中,是否可以通过不同的路径(中间模型)定义多态关系?
我有“付款”、“估价”和“报价”模型,付款具有多态关系,它可以属于报价或估价,同时报价可以有许多估价,因此估价总是属于报价 基本上,所有付款总是属于报价,有时直接,有时通过估算:Php 在Laravel模型中,是否可以通过不同的路径(中间模型)定义多态关系?,php,laravel,eloquent,eloquent-relationship,has-many-polymorphs,Php,Laravel,Eloquent,Eloquent Relationship,Has Many Polymorphs,我有“付款”、“估价”和“报价”模型,付款具有多态关系,它可以属于报价或估价,同时报价可以有许多估价,因此估价总是属于报价 基本上,所有付款总是属于报价,有时直接,有时通过估算: quotes: id estimates: id quote_id payments: id paymentable_id paymentable_type ("App\Models\Quote" or "App\Models\E
quotes:
id
estimates:
id
quote_id
payments:
id
paymentable_id
paymentable_type ("App\Models\Quote" or "App\Models\Estimate")
我的问题是,如何定义关系,以便在使用$quote->payments
时,不仅返回与报价直接相关的付款,还返回与属于该报价的估算相关的付款
有什么建议吗?提前谢谢。是的,有可能的话,你可以试试下面的方法: 定义三种关系: 第一种是直接付款,如下所示:
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());
}
是的,这是可能的,您可以尝试以下方法: 定义三种关系: 第一种是直接付款,如下所示:
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());
}
谢谢,这似乎是接受/投票的最佳解决方案。如果我的答案有任何语法/语义问题,比如
()
,请告诉我。为了纠正我的回答谢谢,这似乎是接受/赞成投票的最佳解决方案。如果我的答案有任何语法/语义问题,比如()
,请告诉我。纠正我的回答