[英]Laravel: add constraint on many-to-many relationships
考虑一下Laravel中这种简单的多对多关系:
class User extends Eloquent {
public function roles()
{
return $this->belongsToMany('Role');
}
}
和
class Role extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
对于保留了user_id
和role_id
的role_user
模式,这是可以的。 但是,如果还有其他限制,我们该怎么办? 例如,在类似Github的应用中,用户在存储库A中是admin,在存储库B中是普通用户。因此,我们将repository_id
添加到role_user
表中,但是当我要查询user->roles
我想在当前存储库中查找它我在session中保留对current_repository_id
引用 。 我应该在模型中进行哪些更改来做到这一点?
注意:我不想更改使用代码中的任何内容! 反正不是在模型声明中放入过滤器逻辑吗? 因为我处于大型项目的中间,因此很难更改每种用法。 可能吗?
//User model
public function roles()
{
$repoID = MyApp::currentRepoID();
return $this->belongsToMany('Role', 'pivot_table_name', 'user_id', 'role_id')
->wherePivot('repository_id', $repoID);
}
如果需要向数据透视表添加其他字段,则应使用-> withPivot()方法。 如果您的数据透视表结构如下:
id | role_id | user_id | repository_id
你应该使用
return $this->belongsToMany('Role', 'pivot_table_name', 'user_id', 'role_id')->withPivot('repository_id');
然后,无论在哪里使用它,都必须执行以下操作:
$role = Role::find(1);
$role->pivot->repository_id;
要么
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->repository_id;
}
看看Eloquent Triple Pivot (也在Packagist上),听起来像它确实满足您的要求。
您将模型设置为User
, Repository
和Role
(一个User
有多个Repository
并且每个Role
都可以有一个Role
)。 然后查看Github页面上的文档(尤其是步骤6),然后在Repository
模型中定义它:
class Repository extends Eloquent {
...
public function getRolesAttribute() {
return $this->getThirdAttribute();
}
}
然后,您可以简单地致电
$user = User::find(1);
$repo = $user->repositories->first();
// or
$repo = $user->repositories->find(73);
$roles = $repo->roles;
// Or the above can be condensed into just...
$roles = User::findOrFail( 1 )
->repositories()
->findOrFail( 73 )
->roles;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.