laravel whereNotIn不工作

时间:2016-12-25 16:09:40

标签: php laravel eloquent

我有两个不同的laravel查询,我想基于第一个查询使用whereNotIn的第二个查询。但whereNotIn似乎无效,因为数据仍然显示。

这是第一个查询

$detailservice = DetailServiceOrder::leftJoin('services', 'detail_service_orders.service_id', '=', 'services.id')
    ->select('detail_service_orders.*',
       'services.service_name')
    ->where('sales_order_id', $id)
    ->get();

这是第二个查询

foreach ($detailservice as $data) {            
        $service[] = Service::whereNotIn('id', [$data->service_id])->get();    
    }

    dd($service);

这里是我的dd($service)结果示例

#attributes: array:4 [▼
      "id" => 2
      "service_name" => "Mail Service"
      "created_at" => "2016-11-26 02:15:24"
      "updated_at" => "2016-11-26 02:15:24"
    ]
 #attributes: array:4 [▼
      "id" => 1
      "service_name" => "Network Maintenance"
      "created_at" => "2016-11-15 07:00:45"
      "updated_at" => "2016-11-15 07:00:45"
    ]

这里是我的dd($detailservice)结果示例

#attributes: array:10 [▼
    "sales_order_id" => 6
    "service_id" => 1
    "order_type" => "add"
    "select_plan" => "test 1"
    "qty" => 2
    "unit_price" => 200.0
    "note" => "testing 1"
    "updated_at" => "2016-12-22 01:34:00"
    "created_at" => "2016-12-22 01:34:00"
    "service_name" => "Network Maintenance"
  ]
#attributes: array:10 [▼
    "sales_order_id" => 6
    "service_id" => 2
    "order_type" => "change"
    "select_plan" => "test 2"
    "qty" => 3
    "unit_price" => 400.0
    "note" => "testing 2"
    "updated_at" => "2016-12-22 01:34:00"
    "created_at" => "2016-12-22 01:34:00"
    "service_name" => "Mail Service"
  ]

上述dd($service)结果不应显示,因为它是在第二次查询时过滤的。

1 个答案:

答案 0 :(得分:1)

您的代码运行正常。首先,它获得ID不为1的结果(因此,它得到2),然后返回ID不是2的结果(返回ID为1的对象)。

如果您想获得ID不是1或2的结果,请使用此代替foreach()

$services = Service::whereNotIn('id', $data->pluck('service_id'))->get();