Laravel(5.7)雄辩的多对多查询

时间:2018-11-17 16:31:04

标签: php laravel eloquent many-to-many relationship

说我有一个用户,角色和数据透视表。我已经为Role和User设置了EmiratesToMany。

用户模型

<?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

数据透视表“ UserRoles”

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

我的问题是如何在数据透视表中获取过滤器。

例如:我只想过滤userIdroleId或两个userId and roleId

如果我在刀片模板中选择user = admin,则希望获得用户拥有的所有角色。 预期结果:

username    roleName

admin       Admin
admin       HR
admin       Account

如果我在刀片模板中选择选项role = HR,那么我想让该角色拥有的所有用户。 预期结果:

username    roleName

admin       HR
johndoe     HR

如果我选择选项user = adminrole = 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

2 个答案:

答案 0 :(得分:3)

您可以尝试根据该示例查询此查询以过滤数据。

函数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();

您还可以根据您的示例尝试使用此查询来过滤数据。此查询将为您提供特定的用户角色,该角色已在role对象中指定。 例如:如果在刀片模板中选择选项角色= 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();

答案 1 :(得分:0)

您可以尝试wherePivot()wherePivotIn()方法:

User::roles()->wherePivot('roleId',$request->roleId)
    ->wherePivot('userId',$request->userId)
    ->get()

https://laravel.com/docs/5.7/eloquent-relationships#many-to-many