Laravel 如何过滤多态关系以仅返回特定模型?
我在定义一个函数来过滤多态关系并只返回一个特定的模型时遇到了一个问题。我将试着解释如下: 假设我有三种型号:Laravel 如何过滤多态关系以仅返回特定模型?,laravel,eloquent,polymorphism,relationship,Laravel,Eloquent,Polymorphism,Relationship,我在定义一个函数来过滤多态关系并只返回一个特定的模型时遇到了一个问题。我将试着解释如下: 假设我有三种型号:A、B和C。型号A可以属于其他两种型号中的任何一种。假设我们正在使用多态性字段名recipient,那么在我们的模型A数据库模式中,我们有recipient\u type和recipient\u id 在型号A上,我有一个名为recipient的默认函数,定义如下: public function recipient() { return $this->morphTo();
A
、B
和C
。型号A
可以属于其他两种型号中的任何一种。假设我们正在使用多态性字段名recipient
,那么在我们的模型A
数据库模式中,我们有recipient\u type
和recipient\u id
在型号A
上,我有一个名为recipient
的默认函数,定义如下:
public function recipient()
{
return $this->morphTo();
}
但是,我需要一个名为b()
的函数,它将返回一个关系,以便可以使用with()
函数与查询生成器一起使用。我可以调用$a->b
,它将返回b
的实例或null,具体取决于a
的实例是否属于b
的实例
对不起,这有点过分了
谢谢你对我的帮助!
干杯 您可以这样定义它 模型A(定义) 现在将其用于即时加载
$records = A::with('bRelation', 'cRelation')->get();
foreach($records as $a){
dd($a->b); //it will return you either instance of `B` or `null`
}
你可以这样定义它 模型A(定义) 现在将其用于即时加载
$records = A::with('bRelation', 'cRelation')->get();
foreach($records as $a){
dd($a->b); //it will return you either instance of `B` or `null`
}
与访问者配合良好:
public function getIssueAttribute()
{
if($this->commentable_type == 'issues') return $this->commentable;
return null;
}
public function getProjectAttribute()
{
if($this->commentable_type == 'projects') return $this->commentable;
return null;
}
public function commentable()
{
return $this->morphTo('commentable');
}
与访问者配合良好:
public function getIssueAttribute()
{
if($this->commentable_type == 'issues') return $this->commentable;
return null;
}
public function getProjectAttribute()
{
if($this->commentable_type == 'projects') return $this->commentable;
return null;
}
public function commentable()
{
return $this->morphTo('commentable');
}
A->recipient
是否根据该A
的recipient\u类型返回B
或C
?对不起,如果我误解了你!A->recipient
是否根据该A
的recipient\u类型返回B
或C
?对不起,如果我误解了你!嗨,rkj,恐怕这似乎没有达到预期效果。DOWN to工作正常,检索模型B
的实例,该实例与收件人id
的id匹配,但以下where子句应用于模型B
的表,而不是模型A
。我们需要将其应用于模型A
table@PapierMoustachio您是对的,我使用访问器对答案进行了更改。检查一下rkj,恐怕效果不理想。DOWN to工作正常,检索模型B
的实例,该实例与收件人id
的id匹配,但以下where子句应用于模型B
的表,而不是模型A
。我们需要将其应用于模型A
table@PapierMoustachio您是对的,我使用访问器对答案进行了更改。检查一下