← 中文资源

简体中文版本

Sequelize

基于 Promise 的 ORM,支持 Postgres、MySQL、MariaDB、SQLite 和 SQL Server,提供模型、迁移和事务。

阅读英文原文

概述

Sequelize 用模型定义表和关系,提供查询、事务和迁移,支持多种关系型数据库。

核心 API

  • new Sequelize():创建 SQL 数据库连接,可配置连接池、日志和方言。
  • define:定义模型,把属性映射到列并设置类型和校验。
  • findAll:按 where、attributes、order、limit 查询,并可 eager include 关联。
  • transaction:在托管事务中运行回调,自动提交或回滚。
  • sync:按模型同步表结构,仅适合开发或测试。
await sequelize.transaction(async (t) => {
  await Account.decrement('balance', { by: amount, where: { id: from }, transaction: t });
  await Account.increment('balance', { by: amount, where: { id: to }, transaction: t });
});

使用注意

生产使用迁移而不是 sync。事务内所有查询都要传 transaction。注意 include 造成的 N+1 和笛卡尔积。连接池大小要与数据库上限匹配。

验证方式

对测试数据库验证模型校验、事务回滚和关联查询,并检查生成的 SQL。