How to get average with orderBy Desc in Laravel 5

后端 未结 3 1133
长情又很酷
长情又很酷 2021-01-20 21:07

I have 2 tables in my database.

books and ratings

in books id, name

in ratings

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 21:50

    You can use a modified withCount():

    $books = Book::withCount(['ratings as average_rating' => function($query) {
        $query->select(DB::raw('coalesce(avg(rating),0)'));
    }])->orderByDesc('average_rating')->get();
    

提交回复
热议问题