public function mainquery() { return Post::selectRaw('posts.*, ' . '(SELECT COUNT(*) FROM comments WHERE comments.post_id = posts.id) as num_comments, ' . 'CASE WHEN myvote.post_id IS NULL THEN 0 ELSE 1 END AS votestate')->with(['user', 'tags', 'dates' => function ($query) { $query->orderBy('date', 'asc'); }])->groupBy('posts.id')->orderBy('score', 'DESC'); }