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

如何将带内连接的Oracle子查询转换为Laravel Eloquent写法

把Oracle SQL转成Laravel Eloquent写法

嘿,我来帮你搞定这个转换!先理清楚你原SQL的核心逻辑:关联EH_APPLICANT和EH_ITEM两张表,筛选出指定用户的记录,按testDate和testTime降序排序后取第一条。下面分两种方式给你写Eloquent代码:

方式一:直接用查询构建器(和原SQL结构最贴近)

首先假设你已经创建了对应的数据模型,如果还没的话,先简单定义下:

// app/Models/Applicant.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Applicant extends Model
{
    protected $table = 'EH_APPLICANT'; // 指定表名
    protected $primaryKey = 'idx'; // 指定主键
    public $timestamps = false; // 如果表没有created_at/updated_at字段,加上这句
}

// app/Models/Item.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $table = 'EH_ITEM';
    protected $primaryKey = 'idx';
    public $timestamps = false;
}

然后就可以写查询代码了:

// 替换成你实际的用户ID变量
$targetUserIdx = 123;

// 执行查询,获取第一条记录
$record = Applicant::select('a.idx', 'a.ntiIdx', 'a.readCnt')
    ->from('EH_APPLICANT as a')
    ->join('EH_ITEM as i', function ($join) use ($targetUserIdx) {
        $join->on('a.netIdx', '=', 'i.idx')
             ->where('a.userIdx', '=', $targetUserIdx);
    })
    ->orderBy('testDate', 'desc')
    ->orderBy('testTime', 'desc')
    ->first();

方式二:利用模型关联(更符合Laravel的优雅风格)

如果你的模型之间定义了关联关系,代码会更简洁。先在Applicant模型里添加关联:

// app/Models/Applicant.php
public function item()
{
    // 关联Item模型,外键是Applicant的netIdx,对应Item的idx
    return $this->belongsTo(Item::class, 'netIdx', 'idx');
}

然后查询代码可以简化成:

$targetUserIdx = 123;

$record = Applicant::select('idx', 'ntiIdx', 'readCnt')
    ->where('userIdx', $targetUserIdx)
    ->whereHas('item') // 对应原SQL的INNER JOIN,确保关联的Item存在
    ->orderBy('testDate', 'desc')
    ->orderBy('testTime', 'desc')
    ->first();

小补充

  • first()方法会自动帮我们获取排序后的第一条记录,对应原SQL里的ROWNUM = 1,Laravel会根据数据库类型自动生成适配的SQL(Oracle下会正确处理行号逻辑)。
  • 如果需要把结果转成数组,可以用$record->toArray();;如果要确保必须有记录,可用firstOrFail()代替first(),没有记录时会抛出404异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:08:09