当针对1以外的值进行过滤时,laravel为什么返回一个对象?

时间:2019-03-20 08:56:25

标签: laravel eloquent

我有以下代码:

    $locations = Location::all();
    if ($request->query('customer_id')) {
        return $locations->where('customer_id', $request->query('customer_id'));
    }

    return $locations;

,如果customer_id为1,则返回一个数组;如果其他任何值,则返回一个对象。这种不一致来自何处? 如果我在结果上调用flatten(),它始终是一致的,但我不知道是什么导致结果差异?

样本输出为: customer_id=1

[
  {
    "id": 2,
    "customer_id": "1",
    "country": "Bulgaria",
    "city": "Sofia",
    "notes": null,
    "created_at": "2019-03-20 08:39:08",
    "updated_at": "2019-03-20 08:39:08",
    "deleted_at": null
  }
]

如果我们得到相同的内容,但customer_id=2(或任何其他ID):

{
  "3": {
    "id": 4,
    "customer_id": "3",
    "country": "Bulgaria",
    "city": "Ruse",
    "notes": null,
    "created_at": "2019-03-20 08:39:08",
    "updated_at": "2019-03-20 08:39:08",
    "deleted_at": null
  }
}

3 个答案:

答案 0 :(得分:1)

尝试一下

$query = Location::query();

if ($request->query('customer_id')) {
    $query =  $query->where('customer_id', $request-customer_id);
}

//you can use another filter if you want. example
if ($request->query('status')) {
    $query =  $query->where('status', 1);
}

$results = $query->get();
return $results;

答案 1 :(得分:0)

您有更好的方法以雄辩的方式完成相同的事情。

 return  Location::
    when($request->query('customer_id'), function($query) use ($request-customer_id) {
              $query->where('customer_id', $request-customer_id);
    })->get()

答案 2 :(得分:-1)

不是使用查询,而是使用first()将has和return作为单行返回

if ($request->has('customer_id')) {
    return $locations->where('customer_id', $request->customer_id)->first();
}