本文介绍了如何在口才上建立条件关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个(简化的)表结构:
I have this (simplified) table structure:
users
- id
- type (institutions or agents)
institutions_profile
- id
- user_id
- name
agents_profile
- id
- user_id
- name
我需要在Users
模型上创建一个profile
关系,但是以下操作无效:
And I need to create a profile
relationship on the Users
model, but the following doesn't work:
class User extends Model
{
public function profile()
{
if ($this->$type === 'agents')
return $this->hasOne('AgentProfile');
else
return $this->hasOne('InstitutionProfile');
}
}
我如何实现这样的目标?
How could I achieve something like that?
推荐答案
让我们采用其他方法来解决您的问题.首先让我们分别设置各种模型的关系.
Lets take a different approach in solving your problem. First lets setup relationship for the various models respectively.
class User extends Model
{
public function agentProfile()
{
return $this->hasOne(AgentProfile::class);
}
public function institutionProfile()
{
return $this->hasOne(InstitutionProfile::class);
}
public function schoolProfile()
{
return $this->hasOne(SchoolProfile::class);
}
public function academyProfile()
{
return $this->hasOne(AcademyProfile::class);
}
// create scope to select the profile that you want
// you can even pass the type as a second argument to the
// scope if you want
public function scopeProfile($query)
{
return $query
->when($this->type === 'agents',function($q){
return $q->with('agentProfile');
})
->when($this->type === 'school',function($q){
return $q->with('schoolProfile');
})
->when($this->type === 'academy',function($q){
return $q->with('academyProfile');
},function($q){
return $q->with('institutionProfile');
});
}
}
现在您可以像这样访问您的个人资料
Now you can access your profile like this
User::profile()->first();
这应该给您正确的配置文件.希望对您有所帮助.
This should give you the right profile. Hope it helps.
这篇关于如何在口才上建立条件关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!