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

如何将指定SQL查询转换为Sequelize ORM?是否有在线转换工具?

关于SQL转Sequelize ORM的在线工具及目标SQL转换方案

在线转换工具说明

目前没有能精准处理所有复杂SQL到Sequelize ORM转换的可靠在线工具。大部分工具仅能处理简单单表查询、基础条件筛选等场景,对于包含子查询、分组聚合这类复杂逻辑的SQL,工具生成的代码往往存在逻辑偏差或无法运行的问题,这类场景建议手动编写ORM代码。

目标SQL的Sequelize ORM写法

假设你已经定义了对应sms表的Sequelize模型Sms,以下是转换后的代码:

首先需要引入Sequelize的操作符和核心方法:

const { Op, Sequelize } = require('sequelize');

写法一:嵌套子查询直接关联

Sms.findAll({
  where: {
    created_at: {
      [Op.in]: Sms.findAll({
        attributes: [[Sequelize.fn('MAX', Sequelize.col('created_at')), 'max_created']],
        group: ['contact_id'],
        raw: true
      })
    }
  },
  order: [['created_at', 'DESC']]
});

写法二:预定义子查询(可读性更强)

// 定义子查询:获取每个contact_id对应的最新created_at
const latestCreatedAtSubQuery = Sms.findAll({
  attributes: [[Sequelize.fn('MAX', Sequelize.col('created_at')), 'max_created']],
  group: ['contact_id'],
  raw: true
});

// 主查询:筛选created_at在子查询结果中的记录并排序
const result = await Sms.findAll({
  where: {
    created_at: {
      [Op.in]: latestCreatedAtSubQuery
    }
  },
  order: [['created_at', 'DESC']]
});

注意事项

  • 确保Sms模型中定义了created_at和contact_id字段(若模型使用驼峰命名,需对应调整为createdAt和contactId,同时确保模型配置了underscored: true以匹配数据库表的下划线命名)。
  • 若使用异步操作,需在函数外层添加async关键字,并使用await获取查询结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:40:29