gizmojo's avatar

Simple count and group by - without writing raw sql

Is it possible to do this in eloquent? All the examples I've found require raw select or counting the colleciton.

SELECT COUNT(category_id) FROM products GROUP BY category_id

When using count() it returns in straight away. Is there a selectCount or something similar?

$total_products = Product::count('category_id')
     ->with('category')
     ->groupBy('category_id');
0 likes
1 reply
shaungbhone's avatar
Level 28

Do you mean like this?

$total_products = Product::with('category')
	 ->withCount('category_id')
     ->groupBy('category_id');
1 like

Please or to participate in this conversation.