Php 从avg()函数生成订单

Php 从avg()函数生成订单,php,mysql,laravel,Php,Mysql,Laravel,我目前正在开发一个Laravel应用程序,我想在这一部分展示最受欢迎的书籍。我将我的评分存储在评分模型中。 我的想法如下,但事实上,它没有起作用。如果有人回答正确,我会非常非常高兴 $book = Book::all(); $ratings = Rating::where('book_id', '=', $book->id)->orderBy(avg('rating')); return view('toprated')->withRatings($ratings); tog

我目前正在开发一个Laravel应用程序,我想在这一部分展示最受欢迎的书籍。我将我的评分存储在评分模型中。 我的想法如下,但事实上,它没有起作用。如果有人回答正确,我会非常非常高兴

$book = Book::all();
$ratings = Rating::where('book_id', '=', $book->id)->orderBy(avg('rating'));
return view('toprated')->withRatings($ratings);
tograted.blade.php

@foreach($ratings as $rating)
    {{ $rating }}
@endforeach

如果需要使用MYSQL函数,请使用
orderByRaw

$ratings = Rating::where('book_id', '=', $book->id)->orderByRaw("avg(rating)");

您可以像这样更新代码:

$ratings = Articles::where('state', '=', '1')
   ->select(array('ratings.*',
       DB::raw('AVG(rating) as ratings_average')
       ))
   ->orderBy('ratings_average', 'DESC')
   ->get();