Laravel sum join with condition



我有产品、仓库、交易和transaction_details表。

$p = Product::leftJoin('transaction_details', 'products.id', '=' ,'transaction_details.product_id')
->leftJoin('transactions', 'transaction_details.transaction_id', '=', 'transactions.id')
->leftJoin('keep_details', 'products.id', '=', 'keep_details.product_id')
->selectRaw(
'products.id,products.product_name productName, products.category_id,
products.sub_category_id, IFNULL(sum(transaction_details.quantity), 0) as totalQty,
products.package_qty, IFNULL(sum(keep_details.quantity), 0) as totalKeep'
)
->groupBy('id','productName','category_id', 'sub_category_id', 'package_qty')
->get();
return new StockCollection($p);

通过使用上面的查询,我能够得到所有预期的产品数量。但在某些情况下,我只想要特定仓库的库存数量。我已经通过添加与事务表相关的仓库Id的where子句来尝试这一点。

$p = Product::leftJoin('transaction_details', 'products.id', '=' ,'transaction_details.product_id')
->leftJoin('transactions', 'transaction_details.transaction_id', '=', 'transactions.id')
->leftJoin('keep_details', 'products.id', '=', 'keep_details.product_id')
->selectRaw(
'products.id,products.product_name productName, products.category_id,
products.sub_category_id, IFNULL(sum(transaction_details.quantity), 0) as totalQty,
products.package_qty, IFNULL(sum(keep_details.quantity), 0) as totalKeep'
)
->where('transactions.warehouse_id', 1) // add this line ####################
->groupBy('id','productName','category_id', 'sub_category_id', 'package_qty')
->get();
return new StockCollection($p);

没有任何错误,但它没有像我预期的那样显示所有的产品,这是因为一些产品在仓库中还没有包含任何交易,但我想显示所有的产品,即使它没有任何交易,但只显示0数量。我知道这不是很复杂,但我只是一个新手,所以我怎么才能做到呢?提前谢谢你……

现在,使用像这样的子查询,它就像预期的那样工作了:

$p = Product::leftJoin(DB::raw('(select td.product_id, td.quantity from products as p left JOIN transaction_details as td on
td.product_id = p.id left join transactions as t on t.id = td.transaction_id
where t.warehouse_id = 1) as details'), 'products.id', '=' ,'details.product_id')
->leftJoin('keep_details', 'products.id', '=', 'keep_details.product_id')
->selectRaw('products.id,products.product_name as productName, products.category_id,
products.sub_category_id, IFNULL(sum(details.quantity), 0) as totalQty,
products.package_qty, IFNULL(sum(keep_details.quantity), 0) as totalKeep')
->groupBy('id','productName','category_id', 'sub_category_id', 'package_qty')
->get();
return new StockCollection($p);

最新更新