laravel 计算laravel数据库中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54415256/
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
Count data from database on laravel
提问by Martin Christopher
On php i could use this code to get how many item on my goods db
在 php 上,我可以使用此代码获取我的商品 db 上的商品数量
$total = 0;
$sql = "select count(*) as total from goods";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$total = $row['total'];
}
}
echo $total;
// example return 5
can i do that on laravel? if i use this code on my controller
我可以在 Laravel 上这样做吗?如果我在控制器上使用此代码
function show(Request $request){
$c = DB::select("SELECT count(*) as total FROM goods");
if($c > 0 ): a ? b;
}
it would get error message since it would return JSON inside array. Are there any better way to do this? Or how to get that total from $c inside controller
它会收到错误消息,因为它会在数组中返回 JSON。有没有更好的方法来做到这一点?或者如何从控制器内部的 $c 中获取总数
回答by Jignesh Joisar
used laravel Aggregatesmethods count
method
使用 laravel聚合方法 count
方法
$count = DB::table('goods')->count();
if($count > 0) {
//more than one raw
}else {
//zero raw
}
回答by Naseh Badalov
You can use count()
function like this:
您可以使用这样的count()
功能:
$count = DB::table('goods')->count();
You can also use Laravel Eloquent on Goodmodel like this:
您还可以在Good模型上使用 Laravel Eloquent,如下所示:
$count = Good::all()->count();
回答by Emeka Okafor
its much cleaner with eloquent
它更干净,雄辩
$c=goods::all()->count();
since the above will pull all collection and count, the more efficient way is
由于以上将拉取所有收集和计数,更有效的方法是
$c=goods::where('value',$val)->get()->count();