首页 文章

多对多查询 - 雄辩

提问于
浏览
0

我有一个用户表,一个角色表和一个role_user表 .

用户有很多角色 .

角色属于许多用户 .

已经在每个模型上定义了关系 .

我需要找出特定用户是否有角色 . 角色可以是字符串或角色数组 .

对于初学者,我试过寻找一个角色头衔 .

我试过了:

Role::with(array('users' => function($query){

      $query->where('title', '=', 'Admin');

  }))->get();

但没有运气 . 如何搜索一个特定的用户ID?

1 回答

  • 0

    如果“admin”是角色的名称,那么您的查询是错误的 .

    Role::with(array('users' => function($query){
      // Use this area to filter users, NOT roles
    }))->get();
    

    你想要这样的东西 .

    // Role "admin" and all the users with that role
    // roles.name = 'admin'
    Role::has('users')->with('users')->where('name', 'admin')->get();
    

    要过滤用户或角色,您只需像往常一样使用Eloquent .

    // All users with the role named "admin"
    User::has('roles')->with(array('roles' => function($q) {
        // roles.name = 'admin'
        $q->where('name', 'admin'); 
    }))->get();
    
    // User named "foo" with the role named "admin" or "public"
    User::has('roles')->with(array('roles' => function($q) {
        // roles.name IN ('admin', 'public')
        $q->whereIn('name', array('admin', 'public'));  
    }))->where('name', 'foo')->get(); // users.name = 'foo'
    

    只需翻转所有内容即可查询角色与用户 .

相关问题