-4
SELECT book_id, COUNT(*)
FROM book
GROUP BY book_id
ORDER BY COUNT(*) DESC

how can convert this sql statment to Laravel ORM ?

Editing :

this sql statement work in MYSQL but not int laravel

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
user1397
  • 1
  • 3

1 Answers1

0

This might do the job:

$result = Book::select(array('book_id', DB::raw('COUNT(*) as count')))
            ->groupBy('book_id')
            ->orderBy(DB::raw('COUNT(*)'), 'desc')
            ->get();

To test/debug your query, add this before it:

DB::listen(function($sql, $bindings, $time) {
    var_dump($sql);
    var_dump($bindings);
});

Or send it to log:

DB::listen(function($sql, $bindings, $time) {
    var_dump($sql);
    var_dump($bindings);
});

This code will plot the builded query into your browser page, like this:

DB::listen(function($sql, $bindings, $time) {
    Log::info($sql);
    Log::info($bindings);
});

And to look at your log:

php artisan tail
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204