现代 Node.js ORM
与数据库交互也可以轻松而优雅。
Sutando 将 Laravel Eloquent 的优雅体验带到 Node.js —— 流畅的查询构造器、表达力强的模型与关联,以及事务、迁移等能力,并原生支持 TypeScript。
$ npm install sutando$ yarn add sutando$ pnpm add sutandoapp / main.ts
import { Model } from 'sutando';
class User extends Model {
declare id: number;
declare name: string;
}
const user = new User();
user.name = 'John';
await user.save();
const users = await User.query()
.where('age', '>', 18)
.get();支持
- MySQL
- PostgreSQL
- SQLite
- MariaDB
- SQL Server
- Oracle
一个不打扰你的 ORM
少写 SQL,同时保留完全的控制权 —— 需要时随时使用原生表达式。
你早已熟悉的查询构造器
链式调用构建查询,读起来就像你原本想写的 SQL,参数绑定交给 Sutando 处理。
- where、whereIn、join 与 orderBy 约束
- count() 与 exists() 聚合查询
- paginate() 分页,chunk() 处理大量数据
- db.raw() 执行原生 SQL,并支持参数绑定
app/queries.ts
import { sutando } from 'sutando';
const db = sutando.connection();
const users = await db.table('users')
.where('votes', '>', 100)
.whereIn('status', ['active', 'pending'])
.orderBy('name')
.take(10)
.get();模型与关联
几行代码定义一个模型,再用直观的方式描述表与表之间的关系,加载关联数据不会退化成 N+1。
- hasOne、hasMany、belongsTo 与 belongsToMany
- with() 预加载,两次查询代替 N+1
- 访问器、修改器、类型转换与查询作用域
- 软删除:restore() 与 forceDelete()
models/user.ts
import { Model } from 'sutando';
class User extends Model {
declare id: number;
declare name: string;
relationPosts() {
return this.hasMany(Post);
}
}
// two queries, not N+1
const user = await User.query().with('posts').find(1);
user.posts.count();可以版本控制的表结构
用迁移构造器定义表结构,提交到仓库,让每个环境都以同样的方式演进。
- 流畅的 schema builder:createTable、字段、索引与外键
- 可回滚的 up / down 迁移
- npx sutando migrate:run 执行,migrate:status 查看状态
- 支持 MySQL、PostgreSQL、SQLite、MariaDB 与 SQL Server
migrations/create_users_table.js
const { Migration } = require('sutando');
module.exports = class extends Migration {
async up(schema) {
await schema.createTable('users', (table) => {
table.increments('id');
table.string('name');
table.string('email').unique();
table.timestamps();
});
}
async down(schema) {
await schema.dropTableIfExists('users');
}
};