The following Query Builder code will give you the exact SQL query you have in your DB::select :
DB::table('wouter_blog_posts') ->whereNotNull('published') ->where('published', 1) ->whereNotNull('published_at') ->whereRaw('`published_at` < NOW()') ->where(DB::raw('1'), '<=', function ($query) use ($tagid) { $query->from('wouter_blog_tags') ->select('count(*)') ->join('wouter_blog_posts_tags', 'wouter_blog_tags.id', '=', 'wouter_blog_posts_tags.tags_id') ->whereRaw('`wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id`') ->whereIn('id', [$tagid[0]->id]); }) ->orderBy('published_at', 'desc') ->skip(0) ->take(10) ->get();
The subquery condition must be canceled because you cannot have the subquery as the first parameter of the where method, and you can still bind the value of the condition. So this is 1 <= (subquery) , which is equivalent to (subquery) >= 1 . The request created by the above code will look like this:
SELECT * FROM `wouter_blog_posts` WHERE `published` IS NOT NULL AND `published` = 1 AND `published_at` IS NOT NULL AND `published_at` < Now() AND 1 <= (SELECT `count(*)` FROM `wouter_blog_tags` INNER JOIN `wouter_blog_posts_tags` ON `wouter_blog_tags`.`id` = `wouter_blog_posts_tags`.`tags_id` WHERE `wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id` AND `id` IN ( ? )) ORDER BY `published_at` DESC LIMIT 10 offset 0
My process when creating more complex queries is to first create them and try in the SQL environment to make sure that they work as requested. Then I implement them step by step using Query Builder, but instead of using get() at the end of the query, I use toSql() , which will give me a string representation of the query that Query Builder will generate, allowing me to compare this with my original query so that make sure he is the same.
source share