计算在 Laravel 中通过查询返回的行数


counting the amount of rows returned with a query in laravel

>我的网站似乎已经停止了,我正在尝试获取数据库返回的行数,但它似乎不想打球......其他人能看到问题吗?

这是我的查询:

$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,因为尚未发送好友请求。我很可能错过了一些完全明显的东西,但任何帮助都会很棒!谢谢!

你有以下代码

$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网站上阅读有关查询生成器的更多信息。

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

echo count($check_friend_request);

如果使用分页器:

$check_friend_request->total();

如果您不使用分页工具:

count($check_friend_request);

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

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

$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);