Skip to content

Instantly share code, notes, and snippets.

@chadidi
Last active June 3, 2020 21:21
Show Gist options
  • Save chadidi/381fd23ea6b8ae5676a32b9273fa1348 to your computer and use it in GitHub Desktop.
Save chadidi/381fd23ea6b8ae5676a32b9273fa1348 to your computer and use it in GitHub Desktop.
posts without eager loads and appends
[2020-06-03 21:20:43] local.INFO: select posts.*, count(likes.id) + count(comments.id) as total_count from `posts` left join `likes` on `posts`.`id` = `likes`.`likable_id` and `likes`.`likable_type` = ? left join `comments` on `posts`.`id` = `comments`.`commentable_id` and `comments`.`commentable_type` = ? where `posts`.`deleted_at` is null group by `posts`.`id` order by `total_count` desc ["posts","posts"]
@chadidi
Copy link
Author

chadidi commented Jun 3, 2020

return Post::setEagerLoads([])
            ->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')
            ->get(12)->each->setAppends([])
            ->paginate();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment