Laravel 4 Eloquent表连接和多个表的where子句

时间:2015-12-20 09:26:15

标签: php laravel join laravel-4 eloquent

您好我正在使用Laravel和Eloquent来存储用户,有个人资料和指定的角色。我的表格结构如下;

users

id | username | email | password | created_at | updated_at

profiles

id | user_id | firstname | created_at | updated_at 

roles 

id | name 

assigned_roles 

id | user_id | role_id

我正在尝试选择角色名称等于admin的所有用户。但是,当我执行以下操作时,我得到一个空数组:

 return \User::with('profile')->join('assigned_roles', function ($join) {
        $join->where('assigned_roles.user_id', '=', 'users.id');
    })->get();

任何想法我做错了什么?

我也在使用Zizaco Entrust和Confide https://github.com/Zizaco/entrust/tree/1.0

1 个答案:

答案 0 :(得分:1)

要获取具有 admin 角色的用户,您需要使用Eloquent的 whereHas()方法:

$admins = \User::with('profile')
  ->whereHas('assigned_roles', function($query) {
    $query->whereName('admin');
  })
  ->get();

我假设您已定义 assigned_roles 关系。如果没有,请在用户和角色之间添加多对多关系:

public function assigned_roles() {
  return $this->belongsToMany('\Your\Model\Namespace\Role', 'assigned_roles', 'user_id', 'role_id');
}