我有这个(简化的)表格 struct :

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');
    }    
}

我怎样才能实现这样的目标?

推荐答案

让我们用不同的方法来解决你的问题.首先,让我们分别为各种模型设置关系.

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');
             });
    }
}

现在你可以像这样访问你的个人资料了

User::profile()->first();

这会给你提供正确的个人资料.希望有帮助.

Laravel相关问答推荐

URL类图中的循环关系

Laravel 10 - 没有 $append 属性的Eloquent 的热切加载

Laravel AppServiceProvider 中的代码在通过 DeployHQ 部署时停止 Composer 和构建

如何避免谷歌翻译翻译:参数

API GET 请求得到与数据库记录不同的结果

如何自定义密码确认不匹配.错误信息?

在 laravel 中查询此类数据的最佳做法是什么?

集成测试模拟外观与注入模拟

你如何找到 Laravel 外观背后的底层类?

如何从 laravel 控制器执行外部 shell 命令?

Laravel - 验证 - 如果字段为空则需要

Laravel 表 * 没有名为 * 的列

为什么我的 Laravel 队列作业(job)在 60 秒后失败?

如何在没有 Artisan 的情况下运行 Laravel?

如何利用 StorageFacade 的 Filesystem 类的 glob 方法?

laravel 4:更新行时如何从列的当前值中减一?

Laravel 仓库

Laravel:array_merge():参数#2不是数组错误

Laravel 从公共删除目录

Laravel 更新查询