在 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
我可以在 Laravel 上这样做吗?如果我在 Controller 上使用此代码
function show(Request $request){
$c = DB::select("SELECT count(*) as total FROM goods");
if($c > 0 ): a ? b;
}
它会收到错误消息,因为它会在数组中返回 JSON。有没有更好的方法来做到这一点?或者如何从 Controller 内部的 $c 中获取总数
最佳答案
使用过 Laravel Aggregates方法 count
方法
$count = DB::table('goods')->count();
if($count > 0) {
//more than one raw
}else {
//zero raw
}
关于laravel - 计算laravel数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54415256/