Ju *_*ira 7 relationships laravel eloquent
我有这个(简化的)表结构:
users
- id
- type (institutions or agents)
institutions_profile
- id
- user_id
- name
agents_profile
- id
- user_id
- name
Run Code Online (Sandbox Code Playgroud)
我需要profile在Users模型上创建一个关系,但以下方法不起作用:
class User extends Model
{
public function profile()
{
if ($this->$type === 'agents')
return $this->hasOne('AgentProfile');
else
return $this->hasOne('InstitutionProfile');
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能实现这样的目标?
ose*_*tow 12
让我们采取不同的方法来解决您的问题.首先分别设置各种模型的设置关系.
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');
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以像这样访问您的个人资料
User::profile()->first();
Run Code Online (Sandbox Code Playgroud)
这应该给你正确的配置文件.希望能帮助到你.
您可以通过使用另一种方法来做到这一点,请检查:
博客 Post 和 Video 模型可以与 Tag 模型共享多态关系。使用多对多多态关系可以让您拥有一个在博客文章和视频之间共享的唯一标签列表。首先,让我们检查一下表结构:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations
| 归档时间: |
|
| 查看次数: |
6416 次 |
| 最近记录: |