问题
I can't get this query to work!
return Post::selectRaw('likes_count + comments_count as total_count')
->withCount(['likes', 'comments'])
->groupBy('posts.id')
->orderByDesc('total_count')
->paginate();
It works this way below but I want all the counts and something performant!
return Post::leftJoin('likes', function ($join) {
$join->on('posts.id', 'likes.likable_id')
->where('likes.likable_type', (new Post)->getMorphClass());
})->leftJoin('comments', function ($join) {
$join->on('posts.id', 'comments.commentable_id')
->where('comments.commentable_type', (new Post)->getMorphClass());
})
->selectRaw('posts.*, count(likes.id) + count(comments.id) as total_count')
->groupBy('posts.id')
->orderByDesc('total_count')
->paginate();
回答1:
You probably just need to change a little bit the first query:
return Post::selectRaw('Count(likes.id) + Count(comments.id) as total_count')
->withCount(['likes', 'comments'])
->groupBy('posts.id')
->orderByRaw('(Count(likes.id) + Count(comments.id)) desc')
->paginate();
来源:https://stackoverflow.com/questions/62182454/is-it-possible-to-order-by-the-total-count-of-multiple-tables