I suppose you have a relationship between your models.
$product = Product::has('warehouses', '>', 0)->get();
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I have three tables named "product", "warehouse" and "warehouse_product". I want to get total quantity for each product with selected warehouse. Tables have columns like;
id , name
id , name
id , product_id, warehouse_id, quantity
My code like below;
$products = Product::query() ->addSelect(['total_qty' => WarehouseProduct::query()->selectRaw('SUM(qty)')->whereColumn('product_id', '=', 'products.id')]) ->get();
When i dump my results i get the correct values. But i need record only if the "total_qty" column greater than 0. When i try to add where clause like ->where('total_qty", ">", 0) i get error;
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'total_qty' in 'where clause'
Any solution ideas for my problem? Thank you guys.
Regards.
Guys, i found a solution;
->havingRaw('total_qty > ?', [0])
Please or to participate in this conversation.