3

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.

3
  • Well your current attempt is a raw SQL query, so at the very least you should be using selectRaw, not select. Commented Oct 15, 2020 at 11:49
  • It shows me the following error when substituting select for selectRaw Call to undefined method Illuminate\Database\MySqlConnection::selectRaw() Commented Oct 15, 2020 at 11:53
  • Why are you using GROUP BY without selecting any aggregates? Your current query does not make sense. Commented Oct 15, 2020 at 11:57

2 Answers 2

1

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!!

Sign up to request clarification or add additional context in comments.

Comments

0

@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');

6 Comments

But is a raw query the best option here in general? Assuming fluent builder supports parameters, wouldn't it make more sense to use that instead?
GROUP BY with SELECT * is generally forbidden.
This is the only way to use raw sql querry in Laravel @TimBiegeleisen
I get the following error SQLSTATE[42000]: Syntax error or access violation: 1055 'propuesta.reservas.id' isn't in GROUP BY (SQL: SELECT * FROM reservas WHERE cliente_id = :id AND dia >= :date GROUP BY dia)
@TimBiegeleisen you are right but he mention in question how to run sql query .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.