2

I have ran into a weird issue with Laravel where the equals sign does not return any values within a where clause. But the weirdest part is that if I use a != instead I get results!

Widgets 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
)

Heres my code. Returns an empty array (but should return rows 2 and 3)

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

Same code but with != instead, returns rows 1, 4 and 5... (as it should)

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

What is going on?? Is this a bug? Has anyone ran into this issue before?

moonman
  • 51
  • 1
  • 6

1 Answers1

1

Your query is saying "get every Widget with an id of x and an id of y and an id of z (etc.)". You want "get every Widget with an id of x OR an id of y OR an id of Z". If you change to this, it should work:

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

The reason != is working the other way is because that query is saying "get every Widget without an id of x and without an id of y and without an id of z (etc.)".

There's actually an easier way to do this though:

$q = Widgets::whereIn('id', $array_of_ids)->get()->toArray();
Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • This worked! It makes sense now that my original code would not iterate properly. I would mark this a useful but I don't have 15 rep just yet... Thanks for your help @JoelHinz – moonman Feb 19 '15 at 18:52