【问题标题】:Is it possible to dynamically set model for Eloquent Relationships?是否可以为 Eloquent 关系动态设置模型?
【发布时间】:2018-12-17 21:25:27
【问题描述】:

我有 2 个用户角色。在数据库中,我对两个角色(model_profilesclient_profiles)都有自己的配置文件表。有没有办法动态设置相关的 Profile 模型?我试过这个:

//User model:    
public function profile(){   
  return $this->role == 'model' ? $this->hasOne('App\Models\Model\Profile') : $this->hasOne('App\Models\Client\Profile');
}

但在这种情况下,我不能使用像 User::with('profile')->whereIn('id', [1,2,3])->get(); 这样的 Eloquent 方法,因为在加载用户模型之前,$this->rolenull

有什么方法可以使用基于用户角色的 Profile 模型并且不会丢失任何 Eloquent 查询方法?

【问题讨论】:

    标签: laravel eloquent laravel-5.7


    【解决方案1】:

    您可以使用多态关系 (More Information)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2017-05-07
      • 2020-01-15
      • 2015-10-29
      • 2016-02-26
      相关资源
      最近更新 更多