[英]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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.