簡體   English   中英

如何在遠程關系表Laravel上執行where查詢?

[英]How to perform a where query on a distant relation table Laravel?

我有一個帶有orderLines的訂單,一個orderLine有一個產品。

我只想檢索產品類型!= Partkit的orderLines。 所以我想查詢Product表,其中鍵入!= Partkit。

我該怎么做呢? 訂單查詢:

$order = Order::with('orderLines.product')->where('user_id',Auth()->user()->id)->where('is_order','0')->first();

我試過的

$order = Order::with('orderLines.product')->whereHas('orderLines.product', function($query) {
            $query->where('type','!=', 'Partkit');
        })->where('user_id',Auth()->user()->id)->where('is_order','0')->first();

這總是返回NULL,這不是我想要的並且不正確...

這是一個遙遠的關系。

任何幫助表示贊賞

您可以使用has()方法。

$order = Order::with('orderLines.product')
            ->has('orderLines', function ($query) {
                $query->has('product', function ($query) {
                    $query->where('type', '!=', 'Partkit');
                });
            })
            ->where('user_id',Auth()->user()->id)
            ->where('is_order','0')
            ->first();

這將選擇所有訂單,它們的訂單行和相應的產品, Partkit是訂單行的產品不帶Partkit類型。

不幸的是,您不能對某個關系的關系做一個has,因此您必須像上面那樣嵌套它們。

希望能有所幫助。

您應該嘗試這樣:

$order = Order::with(['orderLines.product' => function($query) {
            $query->where('type','!=', 'Partkit');
        }])
        ->where('user_id',Auth()->user()->id)
        ->where('is_order','0')
        ->first();

請檢查我更新的答案,並讓我知道它的工作與否:

$order = Order::whereHas('orderLines.product', function($query) {
            $query->where('type','!=', 'Partkit');
        })->where('user_id',Auth()->user()->id)->where('is_order','0')->first();

我發現這段代碼可以實現我想要的...

查詢返回全部,然后我手動忘記了我不想要的orderLines。

不是最好的解決方案,但可以完成工作...

$order = Order::with('orderLines.product')->where('user_id',Auth()->user()->id)->where('is_order','0')->first();

foreach($order->orderLines as $key => $orderline) {
    if(isset($orderline->product)){
        if($orderline->product->type == "Partkit") {
            $order->orderLines->forget($key);
        }
    }
}

下面的查詢對我有用:

Order::with(['orderLines' => function($q) {

   $q->with('product')->whereHas('product', function($q2) {
      $q2->where('products.type', '!=', 'Partkit');
   });

}])->where('user_id', \Auth()->user()->id)
->where('is_order', '0')->get();

假設您的products表稱為products ,否則在$q2->where(...)語句中更改表名。

讓我知道是否有幫助。

暫無
暫無

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

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