简体   繁体   English

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

[英]Laravel 4 Eloquent table join and where clause on multiple tables

Hi I'm using Laravel and Eloquent in order to store users, there profile and there assigned roles. 嗨,我使用Laravel和Eloquent来存储用户,那里的个人资料和那里分配的角色。 My table structure is as follows; 我的表结构如下:

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

I'm trying to select all users where there role name is equal to admin. 我正在尝试选择角色名称等于admin的所有用户。 But when I do the following I get an empty array: 但是当我执行以下操作时,我得到一个空数组:

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

Any ideas what I'm doing wrong? 有什么想法我做错了吗?

Also I am using Zizaco Entrust and Confide https://github.com/Zizaco/entrust/tree/1.0 我也在使用Zizaco Entrust和Confide https://github.com/Zizaco/entrust/tree/1.0

In order to fetch users that have admin role you need to use Eloquent's whereHas() method: 为了获取具有管理员角色的用户,您需要使用EloquentwhereHas()方法:

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

I assume you have assigned_roles relation defined. 我假设您已经定义了assigned_roles关系。 If not, add many-to-many relation between your users and roles: 如果不是,请在用户和角色之间添加多对多关系:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM