Multiple filters in a database query from Laravel

1

When I execute the SQL statement

SELECT * FROM 'payments' WHERE 'estado' IN ('abono', 'adeudo', 'espera') AND 'fecha_pago' < '2016-09-08' ORDER BY 'id'

Result: it brings me the data correctly,

Question: What is the way, to do the same in laravel? I've tried doing things like this and nothing.

return $query->where('estado', 'IN', ['abono','adeudo','espera'])->where('fecha_pago','<','2016-09-08');
    
asked by Luis Cárdenas 08.09.2016 в 23:47
source

2 answers

1

Although your answer is correct, in theory and depending on how you handle it you need the get () method, and the double quotes you use are not necessary in the date variable and according to your initial query you lack the orderBy.

Also, to respect PSR-2, you must insert a space after each argument you pass.

I'm assuming you're inserting this into another query (it would be a subquery) or something like that.

return $query->where('fecha_pago', '<', $var)
    ->whereIn('estado', ['abono', 'adeudo', 'espera'])
    ->orderBy('id');

For future reference of other people who enter this question, I will answer the question in a more neutral way:

Normally you could have a model named Payment, which extends to Illuminate \ Database \ Eloquent \ Model and uses the payments table, and the query would be done as follows:

$resultado = Payment::where('fecha_pago', '<', '2016-09-08')
                 ->whereIn('estado', ['abono', 'adeudo', 'espera'])
                 ->orderBy('id')
                 ->get();

Now, if you do not want or there is no model attached to the table or a relationship, or if you simply want to do without a model, it would be like this:

$resultado = DB::table('payments')
                 ->where('fecha_pago', '<', '2016-09-08')
                 ->whereIn('estado', ['abono', 'adeudo', 'espera'])
                 ->orderBy('id')
                 ->get();

It can even be done with dependency injection, but that is already a more advanced implementation.

    
answered by 09.09.2016 / 01:22
source
0
return $query->where('fecha_pago', '<', "$var")->whereIn('estado', ['abono','adeudo','espera']);

I solved it like that, if there are better suggestions. You are welcome.

    
answered by 09.09.2016 в 01:00