Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aosdev's avatar

Laravel where clause with addSelect()

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;

product

id , name

warehouse

id , name

product_warehouse

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.

0 likes
8 replies
Snapey's avatar

how about just using the pivot table?

DB::table('product_warehouse')
    ->select('product_id','quantity')
    ->where('warehouse_id',1)
    ->where('quantity','>',0)
	->get();
1 like
aosdev's avatar

@Snapey That would be nice but i need other relations from Product model like "product_variants" and "product_images". That's why i start query with Product model.

Snapey's avatar

@aosdev

$products = DB::table('product_warehouse')
    ->select('product_id','quantity','products.*')
    ->where('warehouse_id',1)
    ->where('quantity','>',0)
    ->join('products','product_id','=','products.id')
	->get();

$products->load('product_variants');
1 like
aosdev's avatar

@Snapey That means i have to refactor all my codes, thank you i'll give a try. <3

Snapey's avatar

@aosdev probably won't work thinking about it since these are not eloquent models

if you want models you probably need a whereHas or use the original query just to get the ids and then load all models whereIn

1 like
aosdev's avatar
aosdev
OP
Best Answer
Level 1

Guys, i found a solution;

	->havingRaw('total_qty > ?', [0])
1 like

Please or to participate in this conversation.