如何在Laravel中过滤多对多结构 [英] How to filter many to many structure in Laravel

查看:59
本文介绍了如何在Laravel中过滤多对多结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多用户和角色结构

I got a many to many user and role structure

用户
id
名称

users
id
name

角色
id
名称

roles
id
name

角色用户
user_id
role_id

role_user
user_id
role_id

模型

User.php

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

Role.php

public function users() {
    return $this->belongsToMany('User');
}

角色表中有两个数据 admins members ,我想知道要过滤用户哪个角色是admins.

There are two data admins and members in roles table, I would like to know to to filter users which role is admins.

推荐答案

这应为您提供所有管理员用户.

This should give you all users who are admins.

$users = User::whereHas('roles', function($q) {
    $q->where('name', '=', 'admins');
})->get();

您可以在 http中查看有关 has()方法的更多信息.://laravel.com/docs/eloquent#querying-relations

You can see more information on the has() method at http://laravel.com/docs/eloquent#querying-relations

这篇关于如何在Laravel中过滤多对多结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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