这是我的查询,也可以正常工作:

SELECT sum(r.rating) as rank,b.* FROM books as b
LEFT JOIN ranks as r ON b.id = r.book_id
WHERE 1
GROUP BY (b.id)
ORDER BY rank DESC


现在我想在Laravel中做同样的事情。这是我尝试过的:

// Book model
class Book extends Model
{
    public function ranks()
    {
        return $this->hasMany(Rank::class)->sum("rating");
    }
}

// Controller
$obj = new Book;
$get = $obj->ranks()->orderBy('rating', 'desc')->get();


它引发此错误:


  在整数上调用成员函数groupBy()


知道如何解决此问题吗?

最佳答案

public function ranks() {
    return $this->hasMany(Rank::class)
        ->select('book_id', \DB::raw('sum(`rating`) as `rank`'))
        ->groupBy('book_id');
}

$books = Book::with('ranks')->get();
$sortedBooks = $books->sortByDesc(function($book) {
    return $book->ranks->sum('rank');
});

09-25 21:29