简体   繁体   English

Laravel有很多返回一行,即使它在关系表中有值

[英]Laravel Has Many Returns a Row even it has a value in relations table

Hi I'm using laravel eloquent for my database query. 嗨,我正在使用laravel雄辩的数据库查询。 My Problem is that I can't show the data I wanted to show. 我的问题是我无法显示想要显示的数据。 I have three tables. 我有三张桌子。 Say Users Table, Roles Table and User_Roles table. 说出用户表,角色表和User_Roles表。

Users 用户数

id | id | Name | 姓名|

1 | 1 | John | 约翰|

2 | 2 | Doe | 美国能源部

Roles 的角色

id | id | Name | 姓名|

1 | 1 | Admin | 管理员|

2 | 2 | Employee | 员工|

3 | 3 | Manager | 经理|

User_Roles User_Roles

id | id | user_id | user_id | role_id 角色编号

1 | 1 | 1 | 1 | 2 2

2 | 2 | 1 | 1 | 3 3

3 | 3 | 2 | 2 | 3 3

Users has Many Roles that is saved in User_Roles table. 用户具有许多角色,这些角色保存在User_Roles表中。 My query is "I want to show list of Users that has no Employee roles. In the table I want to show only Doe. How can I make it laravel eloquent. 我的查询是“我想显示没有雇员角色的用户列表。在表中我只想显示Doe。如何使laravel雄辩。

Hope someone can help! 希望有人能帮忙!

Define roles relation in User model User模型中定义roles关系

public function roles() {
    retrun $this->belongsToMany(\Namespace\Role::class);
}

Retrive the role 找回角色

$role = \Namespace\Role::where('name', 'Employee')->first();

Get the users 获取用户

$user = \Namespace\User::whereHas('roles', function($query) use ($role) {
    $query->where('role_id', '!=', $role->id);
})->get();

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

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