我是Laravel的新手,我需要通过获取类似sql以下的结果来进行laravel查询。
SQL
select * from `tb_project_participate`
where
`project_id` = 20 and
`department_id` = 1 and
(
month(`created_at`) = 10 or
(month(`created_at`) = 11) or
(month(`created_at`) = 12)
)
下面是我使用的Laravel代码。
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', $auth->department_id)
->whereMonth('created_at' , 10)
->orWhere(function($query){$query->whereMonth('created_at',11); })
->orWhere(function($query1){$query1->whereMonth('created_at',12); })
->get();
我得到的结果如下,这不是我想要的查询。 SQL
select * from `tb_project_participate`
where
`project_id` = 20 and
`department_id` = 1 and
month(`created_at`) = 10 or
(month(`created_at`) = 11) or
(month(`created_at`) = 12)
感谢有关如何编写Laravel查询以获取结果的建议,对不起,我的英语。非常感谢。
答案 0 :(得分:2)
尝试类似
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', $auth->department_id)
->whereRaw('month(created_at) in (10,11,12))
->get()
或者您也可以这样做
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', $auth->department_id)
->whereIn(DB::raw('month(created_at)'),[10,11,12])
->get()
答案 1 :(得分:1)
请首先搜索它。我认为这个问题在stackoverflow上已经回答了数十次,在网络上已经回答了数百次。
尝试一下:
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', $auth->department_id)
->where(function($query){
$query->whereMonth('created_at' , 10);
$query->orWhere(function($query2){
$query2->whereMonth('created_at',11); });
$query->orWhere(function($query1){
$query1->whereMonth('created_at',12); });
})->get();
或者这个(推荐):
我们尝试使代码尽可能通用,因此我希望将月份作为参数。 对于$ auth也没有真正的理由,因为这是一个额外的操作:$ auth = \ Auth :: user()。只需使用\ Auth :: user()
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', \Auth::user()->department_id)
->where(DB::RAW('month(created_at)'), $months)
->get();
其中$ months是此数组:[10,11,12]
基本上,我们有一个查询,其中添加了所有or语句。 检查手册以供参考。您没有提到该版本,但是最近3年没有做太多更改,因此这里是最新版本:https://laravel.com/docs/5.7/queries#parameter-grouping