Laravel:在多对多关系上添加约束

时间:2014-11-05 10:32:20

标签: php laravel laravel-4 eloquent

在Laravel中考虑这种简单的多对多关系:

class User extends Eloquent {
    public function roles()
    {
        return $this->belongsToMany('Role');
    }
}

class Role extends Eloquent {
    public function users()
    {
        return $this->belongsToMany('User');
    }
}

对于保留role_useruser_id的{​​{1}}架构,这是可以的。 但是,如果我们有其他一些限制呢?例如,在像Github这样的应用程序中,用户是存储库A中的管理员,并且是存储库B中的常规用户。因此我们将role_id添加到repository_id表,但是当我想查询role_user时我想要在当前存储库中查找,我在会话中继续引用user->roles。我应该在模型中做些什么改变呢?


注意:我不想在使用代码中更改任何内容!反正把过滤器逻辑放在模型声明中是不是?因为我处于大项目的中间,很难改变每一种用法。有可能吗?

3 个答案:

答案 0 :(得分:3)

//User model 
public function roles()
{
    $repoID = MyApp::currentRepoID();

    return $this->belongsToMany('Role', 'pivot_table_name', 'user_id', 'role_id')
        ->wherePivot('repository_id', $repoID);
}

答案 1 :(得分:1)

如果您需要向数据透视表中添加其他字段,则应使用 - > 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;
}

答案 2 :(得分:1)

查看Eloquent Triple Pivot(也在Packagist上),它听起来就像你想要的那样。

您将模型设置为UserRepositoryRoleUser有多个Repository,并且可以{每个{1}}。然后查看Github页面上的文档(特别是第6步),并在Role模型上定义它:

Repository

然后你可以简单地调用

class Repository extends Eloquent {
    ...
    public function getRolesAttribute() {
        return $this->getThirdAttribute();
    }
}
相关问题