使用数据透视表where子句构建条件语句

时间:2018-04-11 00:46:08

标签: laravel eloquent laravel-eloquent

嗨我有一个带过滤器的数据表,所以对于每个过滤器,我想使用laravel 5.6从服务器端调整查询

我有一个用户模型:

public function roles()

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

我有一个角色模型

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

我的雄辩声明如下:

   //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",

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

1 个答案:

答案 0 :(得分:0)

经过一些试验和错误后我得到了

    $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();

...这会输出正确的数据,不知道这是不是“这种方式......但是它有效!”