shi*_*sun 1 php laravel eloquent laravel-4
考虑一下Laravel中这种简单的多对多关系:
class User extends Eloquent {
public function roles()
{
return $this->belongsToMany('Role');
}
}
Run Code Online (Sandbox Code Playgroud)
和
class Role extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
Run Code Online (Sandbox Code Playgroud)
role_user可以保留user_id和的模式role_id。但是,如果还有其他限制,我们该怎么办?例如,在类似Github的应用中,用户在存储库A中是admin,在存储库B中是常规用户。因此,我们将其添加repository_id到role_user表中,但是当我要查询时,user->roles我想在当前存储库中查找它,因此我一直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);
}
Run Code Online (Sandbox Code Playgroud)