zoukankan      html  css  js  c++  java
  • 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(IlluminateSupportCollection)对象实例。
    其实,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  }
    复制代码

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

  • 相关阅读:
    用servlet来实现验证码的功能
    Sqlite3 数据库
    xml解析
    Android .9文件
    AsyncTask
    Looper Handler
    URLConnection
    单例模式
    Httpclient访问网络
    json 解析
  • 原文地址:https://www.cnblogs.com/jasonLiu2018/p/11791898.html
Copyright © 2011-2022 走看看