You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:15:02