How to setup conditional relationship on Eloquent

那年仲夏 提交于 2019-12-17 19:22:54

问题


I have this (simplified) table structure:

users
- id
- type (institutions or agents)

institutions_profile
- id
- user_id
- name

agents_profile
- id
- user_id
- name

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?


回答1:


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.




回答2:


you can do this by use another method please check this:

a blog Post and Video model could share a polymorphic relation to a Tag model. Using a many-to-many polymorphic relation allows you to have a single list of unique tags that are shared across blog posts and videos. First, let's examine the table structure:

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




回答3:


Looks like that should be $this->type rather than $this->$type - since type is a property, not a variable.



来源:https://stackoverflow.com/questions/43668153/how-to-setup-conditional-relationship-on-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!