Laravel laravel 查询数据库获取结果实现判断是否为空

jesse · 2019-11-28 11:14:57 · 热度: 24

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

$users = DB::table('users')->where('id',$id)->get();

 if($users){
 //有数据 
 }else{
 //没数据 
 }
 或
 if(is_null($users)){
 //  
 }
 或
 if(empty($users)){
 //
 }

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

var_dump 之后我们很容易发现,即使取到的空结果集,Eloquent 仍然会返回object(Illuminate\Support\Collection) 对象实例。

其实,Eloquent 已经给我们封装几个判断方法如下:

$users = DB::table('users')->where('id',$id)->get();


 if ($users->first()) {
  //
 } 
 if (!$users->isEmpty()) {
  //
 } 
 if ($users->count()) {
  //
 }

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

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册