【问题标题】:How do I set up a deep relation in Eloquent?如何在 Eloquent 中建立深层关系?
【发布时间】:2020-06-19 11:19:07
【问题描述】:

考虑以下世界模型:

  • 一个用户可以是零个或多个用户组的成员
  • 一个用户组可以有零个或多个用户成员
  • 一个 Repo 可以驻留在零个或多个 RepoGroups 中
  • 一个 RepoGroup 可以包含零个或多个 Repos
  • 可以授予用户组对 RepoGroup 的“读取”或“写入”访问权限

实现此模型的(简化的)数据库架构如下所示:

通过 user_group_pivot 表在 User 和 UserGroup 之间建立 Eloquent 多对多关系非常简单,Repo 和 RepoGroup 之间的等价关系也是如此。 access_rights 表是带有附加访问信息的数据透视表,但 ClientGroup 和 RepoGroup 之间的关系也是多对多的,并且同样直接。现在仍然存在以下挑战:

  1. UserGroup 和 Repo 的关系
  2. RepoGroup 和 User 的关系
  3. User 和 Repo 的关系

这是我目前得到的代码:

class User extends Model {
    public function userGroups() {
        return $this->belongsToMany(UserGroup::class, 'user_group_pivot');
    }

    public function repos() {
        # Eloquent wizard can makez magic here?
    }

    public function repoGroups() {
        # Eloquent wizard can makez magic here?
    }
}

class UserGroup extends Model {
    public function users() {
        return $this->belongsToMany(User::class, 'user_group_pivot');
    }

    public function repos() {
        # Eloquent wizard can makez magic here?
    }

    public function repoGroups() {
        return $this->belongsToMany(RepoGroup::class, 'access_rights')
            ->withPivot(['access']);
    }

}

class RepoGroup extends Model {
    public function repos() {
        return $this->belongsToMany(Repo::class, 'repo_group_pivot');
    }

    public function users() {
        # Eloquent wizard can makez magic here?
    }

    public function userGroups() {
        return $this->belongsToMany(UserGroup::class, 'access_rights')
            ->withPivot(['access']);
    }
}

class Repo extends Model {
    public function repoGroups() {
        return $this->belongsToMany(RepoGroup::class, 'repo_group_pivot');
    }

    public function repos() {
        # Eloquent wizard can makez magic here?
    }

    public function repoGroups() {
        # Eloquent wizard can makez magic here?
    }
}

我在网上搜索了类似的例子,但它们要么公然抄袭 Laravel 文档,要么同样微不足道。我一直在玩 Model::hasManyThrough() 关系,但无济于事。因此,我把希望寄托在世界上雄辩的巫师身上。我可以帮忙吗,pliis?

【问题讨论】:

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


    【解决方案1】:

    有可能在不涉及其他关系的情况下进行回购。

    您可以将如下代码添加到User::repos

    $repos = [];
    foreach($user->userGroups() as $userGroup){
       foreach($userGroup->repoGroups() as $repoGroup){
           foreach($repoGroup->repos() as $repo){
              $repos[] = $repo;
       }
    }
    

    如果您担心性能(例如在处理大量用户期间),您可以在从数据库中使用 repos 获取用户期间使用预先加载

    $users = App\User::with(['userGroups.repoGroups.repos'])->get();
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 2021-02-06
      • 2020-06-28
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多