尝试在第二个条件中使用orWhereNull
:
$users = DB::table('users')
->where('col', '=', '')
->orWhereNull('col')
->get();
或者如果您在查询中有多个条件,则必须将两个条件包含在闭包内:
$users = DB::table('users')
->where(function(\Illuminate\Database\Eloquent\Builder $query) {
$query->where('col', '')->orWhereNull('col');
})
->where('col2','val2')
->get();
DB::table('users')->where(function($query) { $query->where(...)->orWhere(...)->orWhere(...); })->where(...)->where(...)->get();
。这将在生成的SQL语句中将基于闭包的条件封装在括号中。 - Soulriser$user->albums()->whereRaw("NOT col > ''")
这种方式可以同时检查两个条件
$users = DB::table('users')
->whereRaw('col = "" OR col IS NULL')
->get();
因此,总结一下您的答案:
OR 条件
$users = DB::table('users')
->where('col', '=', '')
->orWhere('col','=','')
->whereNull('col')
->get();
AND 和 OR 条件
$users = DB::table('users')
->where(function($query) { $query->where('col','=','')->orWhere('col','=','')->whereNull('col'); })
->where('col','=','')
->get();
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
///...
Builder::macro('whereNullOrEmpty', function ($field) {
return $this->where(function ($query) use ($field) {
return $query->where($field, '=', null)->orWhere($field, '=', '');
});
});
Builder::macro('whereNotNullOrEmpty', function ($field) {
return $this->where(function ($query) use ($field) {
return $query->where($field, '<>', null)->where($field, '<>', '');
});
});
}
//...
}
然后像这样调用它:
if($nullOrEmpty){
$builder->whereNullOrEmpty('col');
}else{
$builder->whereNotNullOrEmpty('col');
}
你必须调用两个命令:
where($field, '<>', null);
where($field, '<>', '');
(where col = null or where col = '')
不太确定,但这可能有效:
$user->albums()->where_in('col', array(NULL,''));
=
操作符进行比较,所以这不起作用。此外,方法的名称是whereIn
而不是where_in
。应该测试过它,而不是写下“不确定,但这可能起作用”... - jsphplCollection
对象上而不是查询构造器上运行 whereIn('col', [null, ''])
,它是会工作的。例如:$user->albums->whereIn('col', [null,'']);
。请注意使用了魔术关系属性 albums
,它返回一个集合,而不是返回查询构建器实例的 albums()
。 - Soulriser