以多对多关系让除管理员以外的所有用户 [英] Getting all users except admins in many-to-many relationship

查看:61
本文介绍了以多对多关系让除管理员以外的所有用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户表和角色表,它们以role_user表中的多对多关系进行连接.我想要获得除具有管理员角色的用户以外的所有用户,我要包括没有任何角色的用户.基本上,除管理员外的所有用户.

I have a users table and roles table, connecting them in many-to-many relationship in role_user table. I want to get all users except the users that have admin role, I want to include the users that do not have any roles. Basically all users except admins.

推荐答案

在用户模型中添加关系.

Add a relation in the User model.

User.php

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

用于检索

$user = User::whereHas('roles', function($query){
   $query->where('name', '<>', 'admin') // role with no admin
});

用于普通MYSQL

SELECT u.* FROM users u 
    INNER JOIN role_user ru ON ru.user_id = u.id
    INNER JOIN roles r ON r.id = ru.role_id WHERE r.name <> 'admin';

这篇关于以多对多关系让除管理员以外的所有用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆