首页 > 解决方案 > How do I set up a deep relation in Eloquent?

问题描述

Consider the following world model:

The (simplified) database schema implementing this model looks like this:

Database schema

Setting up the Eloquent many-to-many relationship between User and UserGroup via the user_group_pivot table is straight forward, as is the equivalent relationship between Repo and RepoGroup. The access_rights table is a pivot table with additional access information, but the relationship between ClientGroup and RepoGroup is also many-to-many, and equally straight forward. Now the following challenges remain:

  1. The relationship between UserGroup and Repo
  2. The relationship between RepoGroup and User
  3. The relationship between User and Repo

This is the code I've got so far:

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?
    }
}

I've scoured the web looking for examples similar to this, but they either blatantly plagiarize the Laravel docs or are equally trivial. I've been playing around with the Model::hasManyThrough() relationship, but to no avail. Hence I put my hopes in the Eloquent wizards of the world. I can haz helps, pliis?

标签: phplaraveleloquentmany-to-manyhas-many-through

解决方案


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

您可以在下面添加这样的代码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();

推荐阅读