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


Laravel 4 Eloquent table join and where clause on multiple tables

嗨,我使用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和Confidehttps://github.com/Zizaco/entrust/tree/1.0

为了获取具有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');
}