簡體   English   中英

Laravel 和條件連接

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM