2016-04-19 7 views
0

人気カテゴリーを選択したカテゴリとサービスLaravel 5は、テーブルに参加して、私は2つのテーブルを持っている

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にそれを制限したいです最も使用されるカテゴリ
望ましい結果:私はjoinまたはleftjoinこれらのテーブルに持っているよう

category name | category count 
    category_1 |   3 
    category_2 |   1 

は思えるが、それは私

ためにかなり混乱して

答えて

0
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(); 
1

あなたが正しいです、あなたは結合を使用する必要があります。

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; 

P.S.:あなたはこれを試してみてください雄弁でそれをrewrtie、またはDB::raw()を使用することができます私はそれを確認しませんが、動作する必要があります。 Good tutorial about joins

関連する問題