Laravel 等于在 Where 子句中返回空

Laravel Equals Returning Empty In Where Clause

我 运行 遇到了 Laravel 的奇怪问题,其中等号 return where 子句中没有任何值。但最奇怪的是,如果我使用 != 代替,我会得到结果!

小部件 Table

+----+-------------+-------------+
| id |    title    | widget_data |
+----+-------------+-------------+
| 1  |  my widget  |     xyz     |
+----+-------------+-------------+
| 2  |  the widget |     xyz     |
+----+-------------+-------------+
| 3  |  da widget  |     xyz     |
+----+-------------+-------------+
| 4  |  our widget |    xyz...   |
+----+-------------+-------------+
| 5  |  etc...     |    etc...   |
+----+-------------+-------------+

$array_of_ids

array(
   [0] => 2,
   [1] => 3
)

这是我的代码。 Returns 一个空数组(但应该 return 第 2 行和第 3 行)

$q = Widgets::where(function($query) use ($array_of_ids){
   foreach ($array_of_ids as $key => $value){
     $query->where('id', '=', $value);
   }
})->get()->toArray();

相同的代码,但用 != 代替,return第 1、4 和 5 行...(应该如此)

$q = Widgets::where(function($query) use ($array_of_ids){
   foreach ($array_of_ids as $key => $value){
     $query->where('id', '!=', $value);
   }
})->get()->toArray();

这是怎么回事??这是一个错误吗?有没有人 运行 以前处理过这个问题?

您的查询是 "get every Widget with an id of x and an id of y and an id of z (etc.)"。你想要"get every Widget with an id of x OR an id of y OR an id of Z"。如果你改成这个,它应该可以工作:

$q = Widgets::where(function($query) use ($array_of_ids){
   foreach ($array_of_ids as $key => $value){
     $query->orWhere('id', '=', $value);
   }
})->get()->toArray();

!= 以另一种方式工作的原因是因为该查询说 "get every Widget without an id of x and without an id of y and without an id of z (etc.)".

虽然实际上有一种更简单的方法可以做到这一点:

$q = Widgets::whereIn('id', $array_of_ids)->get()->toArray();