如何在 Eloquent 上设置条件关系 [英] How to setup conditional relationship on Eloquent

查看:24
本文介绍了如何在 Eloquent 上设置条件关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个(简化的)表结构:

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.

这篇关于如何在 Eloquent 上设置条件关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆