php 计算laravel中查询返回的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19038779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
counting the amount of rows returned with a query in laravel
提问by Daniel Morgan
I appear to have hit a halt with my website, I'm trying to get the number of rows returned by the database but it doesn't seem to want to play ball... can anybody else see the problem?
我的网站似乎停止了,我正在尝试获取数据库返回的行数,但它似乎不想玩球……其他人能看到这个问题吗?
This is my query:
这是我的查询:
$check_friend_request = DB::table("friend_requests")
->where("request_sent_by_id", Auth::user()->user_id && "request_sent_to_id", $curUserID[1]);
and this is how I'm "attempting" to count the number of rows
这就是我“试图”计算行数的方式
$cfr = count($check_friend_request);
whenever I try to echo $cfr it returns 1 but should return 0 because a friend request hasn't been sent. I've more than likely missed something completely obvious, but any help would be fantastic! thank you!
每当我尝试 echo $cfr 它返回 1 但应该返回 0 因为尚未发送好友请求。我很可能错过了一些完全明显的东西,但任何帮助都会很棒!谢谢你!
回答by The Alpha
You have following code
你有以下代码
$check_friend_request = DB::table("friend_requests")
->where("request_sent_by_id", Auth::user()->user_id && "request_sent_to_id", $curUserID[1]);
It should be
它应该是
$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();
Then, you can use
然后,您可以使用
if($check_friend_request){
//...
}
Also, count($check_friend_request)
will work because it returns an array of objects. read more about Query Builderon Laravel
Website.
此外,count($check_friend_request)
会起作用,因为它返回一个对象数组。在网站上阅读有关查询生成器的更多信息Laravel
。
回答by Rakesh Kumar
To count returned result from array in Laravel, just use simple count for array i.e.
要计算 Laravel 中数组返回的结果,只需对数组使用简单的计数即
echo count($check_friend_request);
回答by hktang
If you use a paginator:
如果您使用分页器:
$check_friend_request->total();
If you don't use a paginator:
如果您不使用分页器:
count($check_friend_request);
See documentation at https://laravel.com/docs/5.3/pagination
回答by Soniya Reddy Basireddy
Try this one hope it will help for you.
试试这个希望对你有帮助。
$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);