中文文档摘要:
Sequelize 是一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能。
安装
$ node -v v16.14.0 pnpm i sequelize mysql2
依赖 package.json
{ "type": "module", "dependencies": { "mysql2": "^2.3.3", "sequelize": "^6.21.3" } }
定义模型
import { Sequelize, DataTypes } from "sequelize"; // 连接到数据库 const sequelize = new Sequelize("mysql://root:123456@127.0.0.1:3306/data"); // sequelize.define(modelName, attributes, options) const User = sequelize.define( "User", { name: DataTypes.STRING, age: DataTypes.INTEGER, }, { // 表名 tableName: "table_user", // 时间戳,默认createdAt/updatedAt timestamps: false, createdAt: "create_time", updatedAt: "update_time", } );
CURD示例
async function createRow() { const user = await User.create({ name: "Jane", age: 23 }); // INSERT INTO `table_user` (`id`,`name`,`age`) VALUES (DEFAULT,?,?); console.log(user.toJSON()); // { id: 8, name: 'Jane', age: 23 } } async function selectRow() { const user = await User.findByPk(3); // SELECT `id`, `name`, `age` FROM `table_user` AS `User` WHERE `User`.`id` = 3; console.log(user.toJSON()); // { id: 3, name: 'Tom', age: 23 } } async function selectRows() { const users = await User.findAll(); // SELECT `id`, `name`, `age` FROM `table_user` AS `User`; console.log(users.map((user) => user.toJSON())); // [ // { id: 2, name: 'Tom', age: 23 }, // ] } async function updateRow() { const result = await User.update( { name: "Doe" }, { where: { id: 1, }, } ); // UPDATE `table_user` SET `name`=? WHERE `id` = ? console.log(result); // [ 1 ] } async function deleteRow() { await User.destroy({ where: { id: 1, }, }); // DELETE FROM `table_user` WHERE `id` = 1 } (async () => { // await createRow() // await selectRow(); // await selectRows(); // await updateRow(); // await deleteRow(); })();