How to get average with orderBy Desc in Laravel 5

后端 未结 3 1137
长情又很酷
长情又很酷 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:39

    Via Collections*

        $books = Book::with('ratings')
            ->get()
            ->sortBy(function($bk, $key) {
                if($bk->rating) {
                    return $bk->rating->rating;
                }
                return null;
            });
    

    Via Joins

      $books = Book::join('rating', 'rating.book_id', '=', 'book.id')
                     ->orderBy('ratings.rating', 'desc')
                     ->select('books.*')
                     ->get();
    

提交回复
热议问题