I have this query on mySQL
SELECT updated_at
FROM products
WHERE updated_at >= DATE_ADD(NOW(), INTERVAL -7 DAY)
GROUP BY day(updated_at)
ORDER BY updated_at desc
and I try to apply it on Laravel like this
$date = Products::select('updated_at')
->where('updated_at', '>=', 'DATE_ADD(NOW(), INTERVAL -7 DAY)')
->groupBy('updated_at')
->orderBy('updated_at', 'desc')
->get()
and the results on Laravel is show all data in updated_at column, not just 6 days before now. Is there anything wrong with my query on Laravel, thank you
You have to use whereRaw
instead:
$date = Products::select('updated_at')
->whereRaw('updated_at >= DATE_ADD(NOW(), INTERVAL -7 DAY)')
->groupBy('updated_at')
->orderBy('updated_at', 'desc')
->get()
Another use case is when you need to actually add an interval to a date column and compare that to now(), like comparing 2 days after start_date to now(). You would have to do exactly like this (laravel 5.7):
->whereRaw('start_date + interval 2 day >= ?', [now()]);
I found the working answer here: https://laracasts.com/discuss/channels/eloquent/adding-days-to-a-date-in-a-where-query
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.