Niyaz
Niyaz

Reputation: 947

How can I grab the top 10 most occurring values in mysql table column using laravel eloquent?

I want to grab the top 10 most occurring values in mysql table column using laravel 4.2.

For example, the top 10 occurring products and its counts, as in the below raw MySQL query:

SELECT `product_id`, COUNT(*)
FROM `product_details`
GROUP BY `product_id`
ORDER BY COUNT(*) DESC
LIMIT 10;

Upvotes: 0

Views: 695

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521409

Try this syntax:

DB::table('product_details')
        ->select('product_id', DB::raw('COUNT(*) AS cnt'))
        ->groupBy('product_id')
        ->orderByRaw('COUNT(*) DESC')
        ->take(10)
        ->get();

Upvotes: 1

Related Questions