dt888999 2014-11-05 02:32
浏览 107
已采纳

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?

  • 写回答

3条回答 默认 最新

  • douchai7891 2014-11-05 03: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部