I have the following relationship: Items has many Records (Records.item_id references Items.id).
I have this query working fine:
$items = Item::addSelect(['quantity_sum' => Record::selectRaw('sum(quantity) as total') ->whereColumn('item_id', 'items.id') ->groupBy('item_id') ]) ->get(); But I need to get just the Items where the sum of records.quantity is lower than 1. I have tried add ->where('quantity_sum', '1') but I get this error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'quantity_sum' in 'where clause' (SQL: select
items.*, (select sum(quantity) as total fromrecordswhereitem_id=items.idgroup byitem_id) asquantity_sumfromitemswherequantity_sum= 1)
Why can't I use the quantity_sum alias?
How can I filter only the Items whose sum in the Records.quantity column is less than 1?