【问题标题】:laravel hasmanythrough on manytomanylaravel hasmanythrough on manytomany
【发布时间】:2016-03-04 14:48:30
【问题描述】:

我正在构建一个用户和角色之间的多对多以及角色和权限之间的多对多的应用程序。 我想获得具有 hasManyThrough 的用户的权限,但它不起作用。此关系需要角色表中的 user_id,但由于它们是多对多的,因此当然没有。 谁有解决方法?

【问题讨论】:

    标签: php orm eloquent many-to-many has-many-through


    【解决方案1】:

    hasmanythrough 在多对多关系上是不可能的。

    这已经在另一个帖子中得到了更详细的回答: HasManyThrough with one-to-many relationship

    您也可以参考:http://laravel-tricks.com/tricks/i-has-many-through-relation-laravel-the-missed-shortcut

    【讨论】:

      【解决方案2】:

      有一个 Laravel 5.5 composer 包可以执行多级关系(深度)

      包装: https://github.com/staudenmeir/eloquent-has-many-deep

      例子:

      User → 属于许多 → Role → 属于许多 → Permission

      class User extends Model
      {
          use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
      
          public function permissions()
          {
              return $this->hasManyDeep(
                  'App\Permission',
                  ['role_user', 'App\Role', 'permission_role'], // Pivot tables/models starting from the Parent, which is the User
              );
          }
      }
      

      是否需要定义外键的例子:

      https://github.com/staudenmeir/eloquent-has-many-deep/issues/7#issuecomment-431477943

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-08
        • 2014-09-19
        • 2017-11-12
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-07-24
        • 2014-08-14
        相关资源
        最近更新 更多