typeScript 项目用什么 ORM?试试这个 Eloquent 风格的 Active Record 方案

11 阅读2分钟

TypeScript 项目用什么 ORM?试试这个 Eloquent 风格的 Active Record 方案

背景

Node.js 生态的 ORM 选择不少,但各有取舍:TypeORM 功能全但 API 臃肿、Bug 多年不修;Prisma 设计优雅但 Schema First + 代码生成的模式不适合所有场景;Sequelize 上了年纪,TypeScript 支持是后补的。

如果你喜欢 Active Record 模式,喜欢在模型上直接 .where().with().get() 链式调用,可以看看 Fedaco——一个对标 Laravel Eloquent 的 TypeScript ORM。

快速上手

模型定义用装饰器,简洁直观:

import { Column, Model, PrimaryGeneratedColumn, Table, CreatedAtColumn } from '@gradii/fedaco';

@Table({ tableName: 'posts' })
export class Post extends Model {
  @PrimaryGeneratedColumn()
  declare id: number;

  @Column()
  declare title: string;

  @Column()
  declare content: string;

  @BelongsToColumn({ related: forwardRef(() => User), foreignKey: 'user_id' })
  public user: FedacoRelationType<User>;

  @CreatedAtColumn()
  declare created_at: Date;
}

查询风格跟 Eloquent 几乎一样:

// 条件查询 + 预加载关系
const posts = await Post.createQuery()
  .where('title', 'like', '%TypeScript%')
  .with('user')
  .orderBy('created_at', 'desc')
  .get();

// 创建
const post = await Post.createQuery().create({ title: 'Hello', content: '...', user_id: 1 });

// 更新 & 删除
await post.Update({ title: 'Updated' });
await post.Delete();

核心亮点

关系支持完整:HasOne、HasMany、BelongsTo、BelongsToMany、HasManyThrough、多态关系(MorphTo/MorphMany/MorphToMany)全覆盖,还支持 onQuery 钩子给关系加默认约束。

驱动解耦:核心包 @gradii/fedaco 不绑定任何数据库客户端,SQLite、MySQL、MariaDB、PostgreSQL、SQL Server 各有独立驱动包,按需安装:

npm install @gradii/fedaco @gradii/fedaco-mysql-driver

迁移 CLI:内置 fedaco migratemigrate:rollbackmigrate:freshmigrate:status,支持 --connection 参数指定连接,多库项目也能轻松管理。

NestJS 集成@gradii/nest-fedaco 模块开箱即用,支持多连接注册、连接池、优雅关闭。

TypeScript 优先:装饰器元数据驱动,类型推导友好,不需要额外的代码生成步骤。

适合谁

  • 从 PHP/Laravel 转 Node 全栈的开发者(上手零成本)
  • 喜欢 Active Record 而非 Repository/Data Mapper 模式的人
  • NestJS 项目需要一个轻量、不依赖代码生成的 ORM
  • 需要多数据库支持或读写分离的场景

链接

MIT 协议开源,欢迎 Star 和 Issue 反馈。