dt888999
2014-11-05 10:32
浏览 96
已采纳

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

Consider this simple many-to-many relationship in Laravel:

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

and

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

This is ok with schema of role_user that keeps user_id and role_id. But what we if have some other constraints? For example in an app like Github, user is admin in repository A and is regular user in repository B. So we add repository_id to role_user table, but when I want to query user->roles I want to look for that in current repository, that I keep reference of current_repository_id in session. What changes should I do in models to do that?


Note: I don't want to change anything in using-code! Isn't anyway to put filter logic in model declaration? Because I'm at the middle of big project and it's tough to change every usage. Is it possible?

图片转代码服务由CSDN问答提供 功能建议

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

 <  code> class用户扩展Eloquent {
公共职能角色()
 {
返回$ this-&gt; belongsToMany('Role'); 
} 
} 
   
  
 

  class Role extends Eloquent {
 public function users()
 {
返回$ this-&gt; belongsToMany('User');  
} 
} 
   
 
 

role_user 的模式可以保存 user_id role_id 。 但是我们有什么其他约束吗? 例如,在像Github这样的应用程序中,用户是存储库A中的admin,并且是存储库B中的常规用户。因此我们将 repository_id 添加到 role_user 表中,但是当我想要查询时 user-&gt; roles 我想在当前存储库中找到它,我在会话中继续引用 current_repository_id 。 我应该在模型中做些什么更改?


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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douchai7891 2014-11-05 11:53
    已采纳
    //User model 
    public function roles()
    {
        $repoID = MyApp::currentRepoID();
    
        return $this->belongsToMany('Role', 'pivot_table_name', 'user_id', 'role_id')
            ->wherePivot('repository_id', $repoID);
    }
    
    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题