How can I run this SQL query in Laravel?

Viewed 235

I am trying to run this SQL query in many ways in laravel but it shows error.

SELECT * FROM reservas WHERE cliente_id = 2201 AND dia >= '2020-10-15' GROUP BY dia

I have tried to run this query but I get a violation error

DB::select('SELECT * FROM reservas WHERE cliente_id = :id AND dia >= :date GROUP BY dia', ['id' => $id, 'date' => $date]);

The variables that I send have data, that is, the error does not come from empty variables, far from it, but the error comes from the query. It should be noted that this query does work in SQL.

2 Answers

You need to write your query like groupBy(DB::raw('dia'))

\DB::table('reservas')->where('cliente_id',$id)->where('dia',$date)->get()->groupBy('dia');

You need to change false in config/database.php Like strict => false if your groupBy not working properly.

Hope its work!!

@Cristian you need to use DB::raw inside DB::select

using like that

DB::select(DB::raw("SELECT * FROM reservas WHERE cliente_id = :id AND dia >= :date GROUP BY dia"), ['id' => $id, 'date' => $date]);

other wise used this if you don't want to set strict type false.

DB::table('reservas')->where('cliente_id',$id)->where('dia',$date)->get()->groupBy('dia');
Related