如何在Eloquent上设置条件关系

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)

我需要profileUsers模型上创建一个关系,但以下方法不起作用:

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)

这应该给你正确的配置文件.希望能帮助到你.

  • 由于范围运行时未加载“用户”对象,因此这将不起作用。因此,加载用户时“$this->type”将始终为空。您必须首先加载用户,然后*然后*运行其余代码。 (4认同)

Mor*_*far 5

您可以通过使用另一种方法来做到这一点,请检查:

博客 Post 和 Video 模型可以与 Tag 模型共享多态关系。使用多对多多态关系可以让您拥有一个在博客文章和视频之间共享的唯一标签列表。首先,让我们检查一下表结构:

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations

  • 我认为多态就在这里,但您需要稍微重组您的数据库。 (3认同)
  • 谢谢,但多态关系在这里不适用。 (2认同)