簡體   English   中英

WhereHas與WhereRaw建立一對多關系(Laravel)

[英]WhereHas with WhereRaw on one to many relationship (Laravel)

我的系統中有一個訂單表和一個order_details表。 訂單表和訂單明細表之間的關系是一對多的,這意味着一個訂單有很多訂單明細。

現在的問題是我試圖用存儲在order_details表中的項目數量a過濾訂單。

我做對的事情都知道嘗試使用whereHas

if ($request->has('quantity') && $request->quantity != null){
        $query = $query->whereHas('orderDetails',function ($q) use ($request){
            $q->whereRaw('SUM(Quantity) >= '.$request->quantity);
        });
    }
$orders = $query->orderBy('OrderID','desc')->get();

但這會引發錯誤

General error: 1111 Invalid use of group function (SQL: select * from `orders` where `AddedToCart` = 0 and `PaymentSucceeded` = 1 and exists (select * from `order_details` where `orders`.`OrderID` = `order_details`.`OrderID` and SUM(Quantity) >= 12) order by `OrderID` desc)

如果得到解決方案,我將不勝感激

為了能夠使用sum函數,您需要group by數據group by並且正如我所看到的,您正在嘗試按orderID對其進行分組。

這樣的方法可能會有所幫助:

 $ordersIDs = DB::table('orderDetails')
                    ->groupBy('OrderID')
                    ->havingRaw('SUM(Quantity)', '>=', 12)
                    ->pluck('orderID')->toArray();

    $orders = DB::table('orders')
                    ->whereIn($ordersIDs)
                    ->get();

上面的代碼執行兩個SQL查詢,您可以輕松地將它們混合在一起。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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