我有两个表,类别和服务
category_table
+----+--------------+
| id | category |
+----+--------------+
| 1 | category_1 |
| 2 | category_2 |
+----+--------------+
service_table
+----+--------------+-----------+
| id | service | cat_id |
+----+--------------+-----------+
| 1 | service_a | 1 |
| 2 | service_b | 1 |
| 3 | service_c | 1 |
| 4 | service_d | 2 |
+----+--------------+-----------+
我想从服务表中获得类别计数,并使用类别名称显示结果,并将其限制为5个最常用的类别
所需结果:
category name | category count
category_1 | 3
category_2 | 1
似乎我必须join
或leftjoin
这些表,但这对我来说很困惑
你是对的,你必须使用join。你可以用Eloquent重写它,或者使用DB::raw()
试试这个:
SELECT c.category, COUNT(*) AS category_count FROM category_table c LEFT JOIN service_table s ON(c.id = s.cat_id) GROUP BY s.cat_id ORDER BY category_count DESC LIMIT 5;
附言:我不检查,但必须工作。关于加入的好教程
DB::table('category_table')
->leftJoin('service_table', 'category_table.id', '=', 'service_table.cat_id')
->select(DB::raw('category_table.category,count(service_table.cat_id) as category_count'))
->groupBy('service_table.cat_id')
->order_by('category_count', 'desc')
->take(5)
->get();