问题
How do I apply Laravel's Eloquent whereIn() so that it includes null?
I've tried:
User::whereIn("column", [null, 1, 2]) -> get();
And
User::whereIn("column", [DB::raw("null"), 1, 2]) -> get();
But both queries return no results.
Thanks!
回答1:
I don't think you can pass null
in in
mysql statement. If you run the query in mysql console it will skip the null.
Try User::whereNull('column')->orWhereIn('column', array(1, 2))->get();
回答2:
Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition. Just like @Angelin Calu mentioned above in comment section.
The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)
User::where(function ($query) {
$query->whereIn('column',[1,2])->orWhereNull('column');
})->get();
来源:https://stackoverflow.com/questions/40657940/laravel-eloquent-wherein-with-null