I have this query and works fine:
SELECT id_categoria, categorias.descricao_categoria,
MAX(CASE WHEN month(data_compra) = 1 THEN valor ELSE NULL END) as Jan,
MAX(CASE WHEN month(data_compra) = 2 THEN valor ELSE NULL END) as Fev,
MAX(CASE WHEN month(data_compra) = 3 THEN valor ELSE NULL END) as Mar,
FROM `movimentos` INNER JOIN categorias ON id_categoria = categorias.id GROUP BY id_categoria ORDER BY id_categoria;
The result is:
But, at laravel, I can’t get the result
$emps = DB::table('movimentos')
->join('categorias', 'categorias.id', '=', 'movimentos.id_categoria')
->select("id_categoria", "categorias.descricao_categoria", DB::raw (' "MAX(CASE WHEN month(data_compra) = 1 THEN valor ELSE null END) as jan", "MAX(CASE WHEN month(data_compra) = 2 THEN valor ELSE null END) as fev", "MAX(CASE WHEN month(data_compra) = 3 THEN valor ELSE null END) as mar" '))
->orderBY("id_categoria")
->groupBy("id_categoria")
->limit(1)->get();
How do I use/get months fields with foreach??
foreach ($emps as $movimento) {
$output .= '<tr>
<td>' . $movimento->descricao_categoria . '</td>
<td>' . $movimento->??? . '<td>
</tr>';
}
print_r($emps)
show me:
IlluminateSupportCollection Object ( [items:protected] => Array ( [0] => stdClass Object ( [id_categoria] => 1 [descricao_categoria] => Veterinarios [MAX(CASE WHEN month(data_compra) = 1 THEN valor ELSE null END) as jan] => MAX(CASE WHEN month(data_compra) = 1 THEN valor ELSE null END) as jan [MAX(CASE WHEN month(data_compra) = 2 THEN valor ELSE null END) as fev] => MAX(CASE WHEN month(data_compra) = 2 THEN valor ELSE null END) as fev [MAX(CASE WHEN month(data_compra) = 3 THEN valor ELSE null END) as mar] => MAX(CASE WHEN month(data_compra) = 3 THEN valor ELSE null END) as mar
2
Answers
Use
selectRaw()
instead ofDB::raw()
will fix this issue.You can try that and response is a Array(object).