如何在远程关系表Laravel上执行where查询?

时间:2017-08-30 12:53:48

标签: php mysql laravel laravel-5

我订购了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,这不是我想要的,也不是正确的......

这是一个遥远的关系。

感谢任何帮助

4 个答案:

答案 0 :(得分:0)

您可以使用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类型。

不幸的是,你不能对关系的关系做一个,所以你必须像上面那样嵌套它们。

希望有所帮助。

答案 1 :(得分:0)

你应该试试这个:

$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();

答案 2 :(得分:0)

我发现这段代码做了我想要的......

查询返回all,然后我手动忘记了我不想要的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);
        }
    }
}

答案 3 :(得分:0)

对我有用的是以下查询:

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(...)语句中的表名。

如果有帮助,请告诉我。