So I have database with amount and created_at field on it and I want to the total amount per month of the current year and or every year.
$sql = 'SELECT SUM(amount) as "Amount",MONTHNAME(created_at) as "Month"
FROM transactions WHERE YEAR(created_at) = YEAR(CURDATE())
GROUP BY YEAR(created_at),MONTH(created_at)';
DB::statement($sql);
Actual Table
ID amount created_at
1 1000 2019-10-24
2 234 2019-11-11
3 122 2019-09-04
4 5200 2019-09-14
Expected Result
ID Amount Month
1 6322 September
2 234 November
Syntax error or access violation: 1055 db.table.created_at isn’t in Group by(SQL: SELECT SUM(amount) as “Total Amount”, MONTHNAME(created_at) as ” Month
Please what is it saying. However if run this query on phpmyadmin it works perfectly well
2
Answers
First set the
strict => false
inappconfigdatabase -> mysql
after that run
php artisan optimize
then
You’re grouping on portions of
created_at
, then referring tocreated_at
itself when youSELECT
. The issue is that only aggregate functions and the things grouped on can be used when you group results in the query. If you useMONTH(created_at)
in select instead ofMONTHNAME
you should be fine (or you couldgroup by YEAR, MONTHNAME
instead and continue to useMONTHNAME
in your projection