如何在Laravel5.6中计算表列categoryname?

js81xvg6  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(343)

使用laravel5.6和mysql。我有下表中的车辆名称

id  name  number   type  
1   def   123      Car
2   lki   589      Van
3   loi   256      Truck
4   oiu   569      Car
5   hyy   589      Van

现在我需要计算每种类型的列数,我不想循环计算。我只需要数一数每种类型,并显示在刀片文件。这样地,

Car 2
Van 2
Truck 1

等。。你怎么能这么做?

hsvhsicv

hsvhsicv1#

你只需要 Group Bytype 列,并使用 Count(*) 要计算行数:

SELECT type, COUNT(*) AS count 
FROM vehicles  
GROUP BY type
gc0ot86w

gc0ot86w2#

只是使用 DB 门面与groupby一起计数

$vehicles= DB::table('vehicles')
                 ->select('type', DB::raw('count(*) as total'))
                 ->groupBy('type')
                 ->get();
ev7lccsx

ev7lccsx3#

这应该管用

$vehiclesInfo = DB::table('vehicles')
                 ->select('type', DB::raw('count(*) as total'))
                 ->groupBy('type')
                 ->get();

有关“分组方式”和“计数”的详细信息,请参阅本教程。高级查询

相关问题