【发布时间】:2020-06-19 11:19:07
【问题描述】:
考虑以下世界模型:
- 一个用户可以是零个或多个用户组的成员
- 一个用户组可以有零个或多个用户成员
- 一个 Repo 可以驻留在零个或多个 RepoGroups 中
- 一个 RepoGroup 可以包含零个或多个 Repos
- 可以授予用户组对 RepoGroup 的“读取”或“写入”访问权限
实现此模型的(简化的)数据库架构如下所示:
通过 user_group_pivot 表在 User 和 UserGroup 之间建立 Eloquent 多对多关系非常简单,Repo 和 RepoGroup 之间的等价关系也是如此。 access_rights 表是带有附加访问信息的数据透视表,但 ClientGroup 和 RepoGroup 之间的关系也是多对多的,并且同样直接。现在仍然存在以下挑战:
- UserGroup 和 Repo 的关系
- RepoGroup 和 User 的关系
- 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