使用 pivot table where 子句构建条件语句

Building conditional statement with pivot table where clause

你好,我有一个带过滤器的数据table,所以对于每个过滤器,我想使用 laravel 5.6

从服务器端调整查询

我有一个用户模型:

public function roles()

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

我有一个榜样

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

我的 eloquent 声明如下所示:

   //filters
$active = false;
$non_active = false;
$role = false;

//check active status
if ($request->get('active') == 'true') {
    $active = true;
}
if ($request->get('non_active') == 'true') {
    $non_active = true;
}
if ($request->get('non_active') == 'true' && $request->get('active') == 'true') {
    $active = false;
    $non_active = false;
}

//check role filter
if ($request->get('role')) {
    $role = true;
}


$users = User::with('roles')
    ->when($active, function ($q) use ($active) {
        return $q->where('active', 1);
    })
    ->when($non_active, function ($q) use ($non_active) {
        return $q->where('active', 0);
    })
    ->when($role, function ($q) use ($role, $request) { //THIS DOES NOT WORK
        return $q->where('roles.id', $request->get('role')); //THIS DOES NOT WORK
    }) //THIS DOES NOT WORK
    ->get();

    return DataTables::of($users)
        ->addColumn('role', function (User $user) {
            return $user->roles->map(function($role) {
                return $role->name;
            })->implode('<br>');
        })
        ->make(true);

最后一部分给出错误说:

"message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.id' in 'where clause' (SQL: select * from `users` where `roles`.`id` = 1)",
    "exception": "Illuminate\Database\QueryException",

如何使用数据透视表 table 在我的查询中添加此 where 语句?

经过反复试验,我得到了

    $users = User::with('roles')
        ->when($active, function ($q) use ($active) {
            return $q->where('active', 1);
        })
        ->when($non_active, function ($q) use ($non_active) {
            return $q->where('active', 0);
        })
        ->when($role, function ($q) use ($role, $request) {
            return $q->whereHas('roles', function ($q) use ($request) {
                $q->where('role_id', $request->get('role'));
            });
        })->get();

...这会输出正确的数据,不知道这是否是 "the" 方式...但它有效!