'How to query multiple whereMonth in orWhere query for laravel
I'm newbie in Laravel and I need to do laravel query by getting result like below sql.
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)
)
Below is Laravel code that I use.
$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();
And I have result as below, that is not a query that I want. 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)
Appreciated for advice how to write Laravel query to get result as whsh, And so sorry for my English. Thank you very much.
Solution 1:[1]
try something like this
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', $auth->department_id)
->whereRaw('month(created_at) in (10,11,12))
->get()
or you can also do as
$participate = ProjectParticipate::where('project_id' , $project->project_id)
->where('department_id', $auth->department_id)
->whereIn(DB::raw('month(created_at)'),[10,11,12])
->get()
Solution 2:[2]
the accepted answer that recommended should be whereIn instead of ->where(DB::RAW('month(created_at)'), $months)
Hope this helps others
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jayashree |
| Solution 2 | Arfani Hidayat |
