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

如何将嵌套查询的MySQL语句转换为Laravel Eloquent或查询构建器?

实现方法

你可以用Laravel查询构造器直接对应原SQL的嵌套逻辑,以下是具体实现:

查询构造器写法

use Illuminate\Support\Facades\DB;

// 构建内层子查询
$subQuery = DB::table('history_penjualan')
    ->select([
        'kodeSales',
        'departemenId',
        'tgl',
        DB::raw('(SELECT SUM(CASE WHEN tgl IN (\'2023-01-01\') THEN score END)) AS `1`')
    ])
    ->whereBetween('tgl', ['2023-01-01', '2023-01-30'])
    ->where('departemenId', '28')
    ->groupBy('tgl');

// 外层查询过滤结果
$result = DB::table($subQuery, 'temp')
    ->select('*')
    ->whereNotNull('`1`')
    ->get();

基于Eloquent模型的写法

如果你的项目中已经定义了对应表的Eloquent模型(比如HistoryPenjualan),也可以用模型来构建子查询:

use App\Models\HistoryPenjualan;

$subQuery = HistoryPenjualan::select([
        'kodeSales',
        'departemenId',
        'tgl',
        DB::raw('(SELECT SUM(CASE WHEN tgl IN (\'2023-01-01\') THEN score END)) AS `1`')
    ])
    ->whereBetween('tgl', ['2023-01-01', '2023-01-30'])
    ->where('departemenId', '28')
    ->groupBy('tgl');

$result = DB::table($subQuery, 'temp')
    ->select('*')
    ->whereNotNull('`1`')
    ->get();

关键说明

  • 用DB::raw()保留原SQL中的子查询和CASE表达式,确保逻辑完全匹配
  • 别名1是数字,需要用反引号包裹避免语法冲突
  • 外层查询将子查询作为临时表temp,通过whereNotNull过滤掉总和为NULL的记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:41:30