Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 4 Laravel 4.2雄辩的获取特定用户和特定角色_Laravel 4_Eloquent - Fatal编程技术网

Laravel 4 Laravel 4.2雄辩的获取特定用户和特定角色

Laravel 4 Laravel 4.2雄辩的获取特定用户和特定角色,laravel-4,eloquent,Laravel 4,Eloquent,在Laravel雄辩的多对多示例中,使用了用户和角色的场景,例如,我有一组用户具有相同的家族“Simpson”名称,我想让他们都扮演“工程师”的角色。我如何使用雄辩的语言来完成这一点?在这个示例中使用了“has”方法,但是如何查询数据库中的用户表和角色表中的值呢 我不是在找 User::find(1)->roles(); 我正在寻找一种方法来做类似的事情 User::whereFamilyName('simpson')->roles()->whereName('Enginee

在Laravel雄辩的多对多示例中,使用了用户和角色的场景,例如,我有一组用户具有相同的家族“Simpson”名称,我想让他们都扮演“工程师”的角色。我如何使用雄辩的语言来完成这一点?在这个示例中使用了“has”方法,但是如何查询数据库中的用户表和角色表中的值呢

我不是在找

User::find(1)->roles();
我正在寻找一种方法来做类似的事情

User::whereFamilyName('simpson')->roles()->whereName('Engineer')
第二个whereName将查询角色表而不是用户表。

您可以尝试以下操作:

$users = User::with(array('roles' => function($query){
    $query->whereName('Engineer');
}))->whereFamilyName('simpson')->get(); // whereFamilyName = family_name in DB

希望您已正确声明了关系,并确保它是
角色
还是
角色
角色
关系表中的
用户
模型。我使用了
角色
,因为您在问题代码中使用了它。

如果您需要获取具有特定角色的用户:

$role = 'Engineer';

// users with family name Simpson having role Engineer
$users = User::whereFamilyName('Simpson')
      ->whereHas('roles', function ($q) use ($role) {
           $q->where('roles.name', $role); // it joins the table so you may need to use prefixed column name, otherwise you can still use dynamic whereName()
      })
      // with('roles') if needed
      ->get();
// returns Collection of User models without roles or with all roles attached to each user if needed
否则,只需连接表即可:

User::whereFamilyName('Simpson')
   ->join('role_user', 'role_user.user_id', '=', 'users.id')
   ->join('roles', 'role_user.role_id', '=', 'roles.id')
   ->whereName('Engineer') // again columns name conflict may occur
   ->get(['users.*']);

所有值都在这里进行了硬编码,以明确说明问题。

感谢deczo,在第一个示例中,如何将参数传递到闭包函数中?工程师可以改为“调酒师”。+1用于使用
whereHas
。许多人想要它,但使用
滥用它。这只会过滤角色对象,而不会过滤主要结果。您应该使用whereHas