如果是get()查询的结果为空,其实$users打印值为object(Illuminate\Database\Eloquent\Collection)#339 (1) { ["items":protected]=> array(0) { } } :
类似为null的还有 pluck('name')等
$users = DB::table('users')->where('id',$id)->get();
不能直接通过
if($users){
//有数据
}else{
//没数据
}
or
if(is_null($users)){
//
}
or
if(empty($users)){
//
}
去判断结果集是否为空,除非将其用 ->toArray(),转成数组才行。
如果用对象操作的话,应该用如下判断:
if ($users->first()) {
//
}
if ($users->count()) {
//
}
if (!$users->isEmpty()) {
//
}
参考脚本之家:Link
如果是first()查询的结果为空,其实$users 打印值为NULL:
类似为null的还有 value('name')等
$users = DB::table('users')->where('id',$id)->first();
可以用:
cempty($users)、is_null($users) 去判断结果是否为空
总结: Important ! ! ! ! ! ! ! ! !
1、如果是使用DB门面的话:
1.1
$users = DB::table('users')->where('id',$id)->get();
get() 如果没有符合条件的查询结果:
$users->first() 返回NULL;$users->isEmpty() 返回 true;$users->count() 返回 0;count($users) 返回 0;
如果有:
$users->first() 返回第一个数组对象;$users->isEmpty() 返回 false;$users->count() 返回 1;count($users) 返回 1;
1.2
$users = DB::table('users')->where('id',$id)->first();
first() 如果没有符合条件的查询结果,则 $users 返回NULL。如果有,则返回一个数组对象。
count($users) 抛出错误:count(): Parameter must be an array or an object that implements Countable;
$users->count() 抛出错误:Call to a member function count() on null;
empty($users) 返回 true; is_null($users) 返回 true;
如果有:
count($users) 抛出错误:count(): Parameter must be an array or an object that implements Countable;
$users->count() 抛出错误:Call to a member function count() on null;
empty($users) 返回 false; is_null($users) 返回 false;
2、如果是使用Eloquent ORM的话:
2.1
$users = Users::where('id',$id)->get();
get() 如果没有符合条件的查询结果:
$users->first() 返回NULL;$users->isEmpty() 返回 true;$users->count() 返回 0;count($users) 返回 0;
如果有:
$users->first() 返回第一个数组对象;$users->isEmpty() 返回 false;$users->count() 返回 1;count($users) 返回 1;
2.2
$users = Users::where('id',$id)->first();
first() 如果没有符合条件的查询结果,则 $users 返回NULL。如果有,则返回一个数组对象(该对象结构和DB不一样)。
count($users) 抛出错误:count(): Parameter must be an array or an object that implements Countable;
$users->count() 抛出错误:Call to a member function count() on null;
empty($users) 返回 true; is_null($users) 返回 true;
如果有:
count($users) 抛出错误:count(): Parameter must be an array or an object that implements Countable;
$users->count() 抛出错误:Call to a member function count() on null;
empty($users) 返回 false; is_null($users) 返回 false;
综上所述:
不管是DB门面还是Eloquent ORM,如果是first()等一维数组或字符串的值,建议使用 empty($users) 或者 is_null($users);
如果是get()等二维数组的值,使用 $users->isEmpty()、$users->count()、$users->first()都可以。建议使用前两个返回值为bool;