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

如何将指定SQL等值子查询转换为Laravel查询构建器语法?

将指定SQL转换为Laravel查询语法

你可以通过Laravel查询构建器的子查询功能直接实现这个等值匹配的相关子查询,不需要依赖whereIn,具体有两种常用实现方式:

方式一:闭包子查询(推荐)

利用where方法接收闭包的特性,自动将闭包内容解析为子查询,完全对应原SQL逻辑:

$results = DB::table('SomeTable')
    ->where('some_column', function ($subQuery) {
        $subQuery->select('some_column')
            ->from('SomeTable as st1')
            ->whereColumn('st1.some_column2', 'SomeTable.some_column2');
    })
    ->get();

方式二:显式子查询构建

先单独构建子查询实例,再传入where方法,逻辑更直观:

$subQuery = DB::table('SomeTable as st1')
    ->select('some_column')
    ->whereColumn('st1.some_column2', 'SomeTable.some_column2');

$results = DB::table('SomeTable')
    ->where('some_column', '=', $subQuery)
    ->get();

两种方式最终生成的SQL都和你提供的原生SQL完全一致,其中whereColumn用于关联外部表与子查询表的字段,保证相关子查询的逻辑正确性。

内容的提问来源于stack exchange,提问作者Christophoros Anthoulakis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:06:26