【问题标题】:counting the amount of rows returned with a query in laravel计算laravel中查询返回的行数
【发布时间】:2013-10-03 01:03:01
【问题描述】:

我的网站似乎停了下来,我正在尝试获取数据库返回的行数,但它似乎不想玩……其他人能看到问题吗?

这是我的查询:

$check_friend_request = DB::table("friend_requests")
->where("request_sent_by_id", Auth::user()->user_id && "request_sent_to_id", $curUserID[1]);

这就是我“尝试”计算行数的方式

$cfr = count($check_friend_request);

每当我尝试回显 $cfr 时,它都会返回 1,但应该返回 0,因为尚未发送好友请求。我很可能错过了一些完全明显的东西,但任何帮助都会很棒!谢谢!

【问题讨论】:

    标签: php sql count laravel laravel-4


    【解决方案1】:

    你有以下代码

    $check_friend_request = DB::table("friend_requests")
    ->where("request_sent_by_id", Auth::user()->user_id && "request_sent_to_id", $curUserID[1]);
    

    应该是

    $check_friend_request = DB::table("friend_requests")
    ->where("request_sent_by_id", "=", Auth::user()->user_id) // "=" is optional
    ->where("request_sent_to_id", "=",  $curUserID[1]) // "=" is optional
    ->get();
    

    然后,你可以使用

    if($check_friend_request){
        //...
    }
    

    另外,count($check_friend_request) 也可以工作,因为它返回一个对象数组。在Laravel 网站上阅读更多关于Query Builder 的信息。

    【讨论】:

    • 我正在使用具有 order_by 和 where 子句的条件连接字符串。那么如何在上面的查询中使用它。你知道我可以与 Laravel 查询构建器一起使用的任何存储库模式吗?
    【解决方案2】:

    要计算 Laravel 中数组返回的结果,只需对数组使用简单的计数,即

    echo count($check_friend_request);
    

    【讨论】:

      【解决方案3】:

      如果你使用分页器:

      $check_friend_request->total();
      

      如果你不使用分页器:

      count($check_friend_request);
      

      请参阅https://laravel.com/docs/5.3/pagination 上的文档

      【讨论】:

        【解决方案4】:

        试试这个,希望对你有帮助。

        $where=array('request_sent_by_id'=>Auth::user()->user_id,'request_sent_to_id'=>$curUserID[1]);
        $check_friend_request = DB::table("friend_requests")->where($where)->get();
        $count=count($check_friend_request);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-02-01
          • 2011-07-22
          • 2010-10-11
          • 1970-01-01
          • 1970-01-01
          • 2013-06-11
          相关资源
          最近更新 更多