Laravel / Eloquent whereIn with null

北慕城南 提交于 2020-12-05 07:13:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!