2


I have this code in laravel to get the products that will run out soon.

$productos = DB::table('productos')
                  ->where('producto_minimo', '>=', 'producto_cantidad')
                  ->get();

And what I get is the following result

Laravel Result

which is not the right result. While in MySql I get the right results whith this query SELECT * FROM productos where producto_minimo >= producto_cantidad;

MySql Result

Update
The query log - DB::getQueryLog() - shows this

  2 => 
    array (size=3)
      'query' => string 'select * from `productos` where `producto_minimo` >= ?' (length=54)
      'bindings' => 
        array (size=1)
          0 => string 'producto_cantidad' (length=17)
      'time' => float 1
5
  • 1
    I'd truly think actually posting the result instead of posting a picture will be easier on all of us. Commented Aug 4, 2014 at 15:47
  • I did, but I couldn't publish the question "too much code" Commented Aug 4, 2014 at 15:48
  • 2
    Have you tried enabling debug=true in database.php so that you can log the actual database queries that are executed? Commented Aug 4, 2014 at 15:49
  • @giannischristofakis the id 4 should be the only result, but I get all the rows in the table. Commented Aug 4, 2014 at 15:50
  • Yeah, first result is way wrong: producto_minimo = 10 which is < than producto_cantidad = 20... Commented Aug 4, 2014 at 15:55

1 Answer 1

4

I assume you've got to use the whereRaw method:

$productos = DB::table('productos')
                  ->whereRaw('producto_minimo >= producto_cantidad')
                  ->get();

Your query will compare the value in the column producto_minimo with the string 'producto_cantidad'

Have a look at Eloquents documentation of advanced wheres:

DB::table('users')
        ->whereExists(function($query)
        {
            $query->select(DB::raw(1))
                  ->from('orders')
                  ->whereRaw('orders.user_id = users.id');
        })
        ->get();

The query above will produce the following SQL:

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)
Sign up to request clarification or add additional context in comments.

Comments

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.