need help in formulating eloquent query, I have this query which uses orWhere however I can't get the correct results when I wanted to added date range in the query.
comment table
id | content | user_id | post_id | created_at | is_owner |
---|---|---|---|---|---|
1 | test | 1 | 1 | 2022-07-09T04:28:50 | false |
2 | test 1 | 2 | 2 | 2022-07-10T04:28:50 | true |
3 | test 2 | 2 | 3 | 2022-07-11T04:28:50 | true |
4 | test 3 | 2 | 2 | 2022-07-11T04:28:50 | false |
5 | test 4 | 3 | 3 | 2022-07-12T04:28:50 | true |
6 | test 5 | 2 | 2 | 2022-07-14T04:28:50 | false |
7 | test 6 | 4 | 2 | 2022-07-14T04:28:50 | false |
8 | test 7 | 5 | 1 | 2022-07-15T04:28:50 | false |
My Answer:
To get the correct results with a date range and orWhere condition in Laravel Eloquent, you can use the following query:
php
$startDate = '2022-07-10';
$endDate = '2022-07-14';
$comments = Comment::where(function($query) use ($startDate, $endDate) {
$query->whereBetween('created_at', [$startDate, $endDate])
->orWhere('is_owner', true);
})->get();
This query will retrieve all comments that fall within the specified date range (from `$startDate` to `$endDate`) or have `is_owner` set to true.
Make sure to adjust the date format and column names according to your actual database schema.
Rate this post
3 of 5 based on 8387 votesComments