Convert SQL query to Eloquent Laravel 5.6

1

I have the following SQL query to get grouped and ordered by months the sum of prices of three products, which makes no problem

 SELECT name, SUM(precio) AS total, mes 
 FROM productos
 GROUP BY mes 
 ORDER BY mes DESC;

The result I get is the following:

+------+-------+---------+
| name | total | mes     |
+------+-------+---------+
| alfa | 138   | marzo   |
| beta | 249   | febrero |
| gama | 372   | enero   |
+------+-------+---------+

I try to make the query in Eloquent, in this way

$data = Producto::
        select(DB::raw("name, mes, SUM(precio) as count"))
        ->groupBy("mes")
        ->orderBy('mes', 'DESC')
        ->get();
    return $data;

But it only works for me if in config/databases.php

  

I set the strict mode to false, which I do not want to do

    
asked by element 28.06.2018 в 02:49
source

1 answer

1

Within the Group by, add the second column name so that I could execute the query and this is the final result

$data = Producto::
        select(DB::raw("name, mes, SUM(precio) as count"))
        ->groupBy("name", "mes")
        ->orderBy('name', 'DESC')
        ->get();
        return $data;
    
answered by 28.06.2018 / 05:48
source