Is it possible to order by the total count of multiple tables?

牧云@^-^@ 提交于 2021-02-11 12:29:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!