【问题标题】:Eloquent hasManyThrough a belongsTo relationship?Eloquent hasManyThrough a belongsTo 关系?
【发布时间】:2020-02-02 07:30:46
【问题描述】:

我正在 Laravel 中实现一个简单的用户角色和权限模型,但我不确定我需要的 Eloquent 关系是否存在。我想返回用户权限的关系,但这是通过角色模型。一个用户通过role_id只有一个角色,但是一个角色有很多权限。

用户 belongsTo => 角色 hasMany => 权限

我想要 User->permissions() 的 Eloquent 关系方法,但 hasManyThrough 不是正确的关系结构。

有什么想法吗?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    像这样。

    用户

    public function permissions()
    {
        return $this->role->permissions;
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用HasManyThrough 关系:

      class User extends Model
      {
          public function permissions()
          {
              return $this->hasManyThrough(
                  Permission::class, Role::class, 'id', null, 'role_id'
              );
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2018-03-08
        • 2020-10-14
        • 1970-01-01
        • 2016-09-26
        • 2019-03-26
        • 2015-07-27
        • 2018-11-28
        • 1970-01-01
        相关资源
        最近更新 更多