【问题标题】:How do I test whether an object returned from Eloquent query is set?如何测试是否设置了从 Eloquent 查询返回的对象?
【发布时间】:2014-04-28 09:56:23
【问题描述】:

我正在测试用户是否在数据库中已经有记录 (d)。

我的查询:

$userResults = Results::where('d','=',Input::get('d'))
                      ->where('user','=',Input::get('user'),'AND')->get();

var_dump 返回

object(Illuminate\Database\Eloquent\Collection)#333 (1) { ["items":protected]=> array(0) { } }

当为空或结果数组时。

如何测试isset 的对象?

【问题讨论】:

    标签: php arrays laravel eloquent


    【解决方案1】:

    您只需使用count 来检查结果:

    // Illuminate\Database\Eloquent\Collection implements Countable interface
    if (count($userResults) === 0) {
      // empty result
    }
    

    或者只使用 isEmpty 方法:

    if ($userResults->isEmpty()) {
      // empty result
    }
    

    【讨论】:

    • 为文档链接添加了荣誉。谢谢。
    【解决方案2】:

    为此使用 Collection 方法:

    $userResults->isEmpty(); // true / false
    

    或者计数,因为 Collection 实现了 Countable 接口

    count($userResults); // 0 if empty
    
    if (empty($userResults)) { // do the job }
    

    【讨论】:

      【解决方案3】:
      if(isset($userResults)){
         //you criteria
      }
      

      if(empty($userResults)){
             //you criteria
          }
      

      【讨论】:

        【解决方案4】:
           if($userResults->count()){
             //your code
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-25
          • 1970-01-01
          • 2011-02-07
          • 1970-01-01
          • 2016-02-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多