laravel查询数据库获取结果如何判断是否为空?

laravel 查询数据库获取结果如何判断是否为空?

 

大家使用的场景是这样的:

复制代码
 1 $users = DB::table('users')->where('id',$id)->get();
 2 
 3 if($users){
 4   //有数据  
 5 }else{
 6   //没数据  
 7 }
 8 或
 9 if(is_null($users)){
10  //        
11 }
12 或
13 if(empty($users)){
14  //
15 }
复制代码

以上方法都是不行的,在使用 Laravel Eloquent 模型时,我们要判断取出的结果集是否为空,但我们发现直接使用 is_null 或 empty是无法判段它结果集是否为空的!!!

var_dump 之后我们很容易发现,即使取到的空结果集,Eloquent 仍然会返回object(Illuminate\Support\Collection)对象实例。
其实,Eloquent 已经给我们封装几个判断方法如下:

$users = DB::table('users')->where('id',$id)->get();
复制代码
1 if ($users->first()) {
2     //
3  } 
4 if (!$users->isEmpty()) {
5     //
6  } 
7 if ($users->count()) {
8     //
9  }
复制代码

以后就这么判断是否为空了!

posted on 2019-11-04 14:30  潇潇六月雨  阅读(355)  评论(0编辑  收藏  举报

导航