问题描述
我正在自定义一个基于 octoberCMS(基于 laravel)的预构建项目。 Bellow 是一个现有的查询片段,我想在其中添加更多“AND”和“OR”条件。
$records = DB::orderBy('id','desc');
$records = $records->where(function($q){
$q->where(function($q){
//Get all employees
$q->where('assigned_id',Auth::getUser()->id);
});
//I need to add "OR (' "column_x" = "whatever" AND "column_y" = "whatever" ')"
$q->orWhere(function($q){
$q->whereHas('manifest',function($q){
$q->where(function($q) {
$q->where('driver_id',Auth::getUser()->id);
});
$q->orWhere(function($q){
$q->where('employee_id',Auth::getUser()->id);
});
});
});
});
解决方法
最好的方法是通过模型提出请求。不要使用构建器
$iUserId = Auth::getUser()->id;
$records = MyModel::where('assigned_id',$iUserId)
->orWhere(function($q) use ($iUserId) {
$q->whereHas('manifest',function($q) use ($iUserId){
$q->where('driver_id',$iUserId);
$q->orWhere('employee_id',$iUserId);
});
});
$records->orderByDesc('id')->get();