如何在Laravel 8中使用Query Builder编写包含子查询的SQL语句
Laravel 8 Query Builder 实现子查询方案
你可以通过两种常见方式实现上述SQL逻辑:
方式1:使用 selectRaw 快速实现
适合简单子查询场景,写法最简洁:
use Illuminate\Support\Facades\DB; $posts = DB::table('posts') ->select('posts.id', DB::raw('(SELECT COUNT(*) FROM post_likes WHERE post_id = 13 AND user_id = 12) as post_like')) ->limit(5) ->get();
如果post_id和user_id是动态变量,推荐用参数绑定避免SQL注入风险:
$postId = 13; $userId = 12; $posts = DB::table('posts') ->select( 'posts.id', DB::raw('(SELECT COUNT(*) FROM post_likes WHERE post_id = ? AND user_id = ?) as post_like'), [$postId, $userId] ) ->limit(5) ->get();
方式2:使用 selectSub 规范实现
这是Laravel官方推荐的子查询写法,子查询逻辑和主查询解耦,可读性和可维护性更高:
use Illuminate\Support\Facades\DB; // 先构造子查询逻辑 $likeCountQuery = DB::table('post_likes') ->where('post_id', 13) ->where('user_id', 12) ->selectRaw('COUNT(*)'); // 主查询绑定子查询 $posts = DB::table('posts') ->select('id') ->selectSub($likeCountQuery, 'post_like') ->limit(5) ->get();
如果是基于Eloquent模型查询,只需要把DB::table('posts')替换为Post::query()即可,其余逻辑保持一致。
内容的提问来源于stack exchange,提问作者Infas Mohammed
相关产品推荐
相关产品推荐

