php - Laravel (5.7) Eloquent Many to Many with query on双方
问题描述
假设我有一个用户、角色和一个数据透视表。我为角色和用户设置了 belongsToMany。
用户模型:
<?php
namespace App;
...
use App\Models\Role;
class User extends Authenticatable
{
...
public function roles()
{
return $this->belongsToMany(Role::class, "UserRoles", "userId", "roleId")
->withPivot("read", "write", "update", "delete")
->withTimestamps();
}
}
榜样:
<?php
namespace App\Models;
...
use App\User;
class Role extends Model
{
...
public function users()
{
return $this->belongsToMany(User::class, "UserRoles", "roleId", "userId")
->withPivot("read", "write", "update", "delete")
->withTimestamps();
}
}
表“用户”:
userId username
1 admin
2 johndoe
3 menghour
表“角色”:
roleId roleName
1 Admin
2 HR
3 Account
数据透视表“用户角色”:
id userId roleId read write update delete
1 1 1 1 1 1 1
2 1 2 1 1 1 1
3 1 3 1 1 1 1
4 2 2 1 0 0 0
5 3 3 1 1 1 0
我的问题是如何在数据透视表中获取过滤器。
例如:我只想过滤userId
或过滤roleId
两者userId and roleId
如果我user = admin
在刀片模板中选择,我想获取用户拥有的所有角色。预期结果:
username roleName
admin Admin
admin HR
admin Account
如果我在刀片模板中选择选项role = HR
,我想获取该角色拥有的所有用户。预期结果:
username roleName
admin HR
johndoe HR
如果我选择选项user = admin
and role = HR
,我只想获得特定的用户和角色。预期结果:
username roleName
admin HR
我累了:
User::whereHas("roles", function ($query) use ($request) {
if ($request->userId) {
$query->where("userRoles.userId", "=", $request->userId);
}
if ($request->roleId) {
$query->where("userRoles.roleId", "=", $request->roleId);
}
})->get();
注意:我使用的是 Laravel 5.7
解决方案
您可以尝试使用此查询根据您的示例过滤数据。
该函数whereHas
用于检索具有给定角色的所有用户。要获取用户的角色,您必须使用with
函数。
$user = User::whereHas('roles', function ($query) use ($request) {
if ($request->roleId) {
$query->where("userRoles.roleId", "=", $request->roleId);
}
})
// It will give you the user's role data.
->with('roles');
// It will check in users table if you have applied the filter by user.
if ($request->userId) {
$user = $user->where("users.id", "=", $request->userId);
}
$user = $user->get();
您还可以尝试使用此查询根据您的示例过滤数据。此查询将为您提供具有您在角色对象中给出的特定角色的用户。例如:如果您在刀片模板中选择选项角色 = HR。
$user = User::whereHas('roles', function ($query) use ($request) {
if ($request->roleId) {
$query->where("userRoles.roleId", "=", $request->roleId);
}
})
// It will give you the user data with a particular given role which you has passed in the request.
->with(['roles' => function($query) use($request) {
if ($request->roleId) {
$query->where("roles.id", "=", $request->roleId);
}
}]);
// It will check in users table if you have applied the filter by user.
if ($request->userId) {
$user = $user->where("users.id", "=", $request->userId);
}
$user = $user->get();
推荐阅读
- graalvm - Graalvm - Java 13,14 支持?
- javascript - 当我从 knex.js 查询时,为什么我的数据库日期值比较不正确?
- reactjs - React-DOM:无法将交易视图画布从“轻量级图表”附加到正文
- python - BERT 中 NER 的正确格式化数据应该是什么样子?
- reactjs - p5.js 的正确类型是什么
- sql - 在不使用“NOT”关键字的情况下从#tbl1 中获取不在#tbl2 中的所有记录
- angular - 从 Angular 更新 json 文件
- javascript - 滚动回顶部时向上滚动到上一个 div
- python - 如何通过networkx使用邻接矩阵将图形转换为所有路径的列表?
- sql - 加快我的 SQL 查询?它给出了执行超时错误