Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where 'less than' query not showing expected results

I am trying to make a database query where I search for all of the items which have a lower current level than low stock level. When running the query I am getting no results and I'm not sure why.

This is my query

public static function getLowStockItemsCache()
{
         dd(\DB::table('items')->where('current_level', '<', 'low_stock_level')->get());
    }

When I die and dump this I get an empty collection.

In my database I have the following records

enter image description here

Both of these fields at set at int(11)

If I reverse the query I get all 13 records.

Am I missing something small, as it's confusing me greatly and should be simple.

like image 732
Chris Townsend Avatar asked Nov 19 '15 12:11

Chris Townsend


1 Answers

The third parameter is the value parameter which means it will be escaped when building the query to avoid SQL injection. If you want to compare two columns, you have to specifically tell the Query Builder that that part of the query should not be processed, either by using whereRaw to pass the raw SQL condition:

\DB::table('items')->whereRaw('current_level < low_stock_level')->get());

Or by using DB::raw() for the value only, so it's not escaped:

\DB::table('items')->where('current_level', '<', DB::raw('low_stock_level'))->get());
like image 200
Bogdan Avatar answered Oct 22 '22 06:10

Bogdan