Skip to content

关联关系概览

IBest ORM 提供了完整的关联关系支持,让您能够轻松处理复杂的数据关系。

核心架构

关联装饰器

  • @HasOne - 一对一关联
  • @HasMany - 一对多关联
  • @BelongsTo - 多对一关联
  • @ManyToMany - 多对多关联

查询方法

  • with() - 预加载关联数据
  • first() / find() - 查询并返回关联数据

级联操作

  • CascadeType.Delete - 级联删除
  • CascadeType.Update - 级联更新
  • CascadeType.Create - 级联创建

快速开始

1. 定义关联关系

typescript
import {
  Table,
  Column,
  PrimaryKey,
  HasOne,
  HasMany,
  BelongsTo,
  ColumnType
} from '@ibestservices/ibest-orm';

@Table()
class User {
  @PrimaryKey()
  id?: number;

  @Column()
  name!: string;

  @HasMany(() => Order, { foreignKey: 'user_id' })
  orders?: Order[];

  @HasOne(() => Profile, { foreignKey: 'user_id' })
  profile?: Profile;
}

@Table()
class Order {
  @PrimaryKey()
  id?: number;

  @Column({ name: 'user_id', type: ColumnType.INTEGER })
  userId?: number;

  @Column({ type: ColumnType.REAL })
  amount?: number;

  @BelongsTo(() => User, { foreignKey: 'userId' })
  user?: User;
}

@Table()
class Profile {
  @PrimaryKey()
  id?: number;

  @Column({ name: 'user_id', type: ColumnType.INTEGER })
  userId?: number;

  @Column()
  bio?: string;

  @BelongsTo(() => User, { foreignKey: 'userId' })
  user?: User;
}

2. 关联查询

typescript
import { getORM } from '@ibestservices/ibest-orm';

const orm = getORM();

// 预加载关联数据
const users = orm.query(User)
  .with('orders')
  .with('profile')
  .find();

// 查询单个用户及关联
const user = orm.query(User)
  .with('profile')
  .where({ id: 1 })
  .first();

console.log(user?.profile?.bio);
console.log(user?.orders?.length);

3. 级联操作

typescript
import { CascadeType } from '@ibestservices/ibest-orm';

// 定义带级联操作的关联
@Table()
class User {
  @PrimaryKey()
  id?: number;

  @Column()
  name!: string;

  @HasMany(() => Order, {
    foreignKey: 'user_id',
    cascade: [CascadeType.Create, CascadeType.Update, CascadeType.Delete]
  })
  orders?: Order[];
}

// 级联创建:自动创建用户及其订单
const user = new User();
user.name = '张三';
user.orders = [
  Object.assign(new Order(), { productName: '商品A', amount: 100 }),
  Object.assign(new Order(), { productName: '商品B', amount: 200 })
];
orm.insertWithRelations(user);

// 级联更新:自动更新用户及其订单
user.name = '张三(VIP)';
user.orders![0].amount = 150;
orm.saveWithRelations(user);

// 级联删除:自动删除用户及其所有订单
orm.deleteWithRelations(user);

详细文档

基础概念

查询策略

数据操作

具体关联类型

性能优化

选择合适的加载策略

场景推荐策略原因
列表页面预加载减少查询次数
详情页面延迟加载按需加载数据
批量操作预加载避免 N+1 问题

避免常见问题

typescript
// ❌ N+1 查询问题
const users = orm.query(User).find();
for (const user of users) {
  // 每次循环都会查询数据库
  const orders = orm.query(Order).where({ userId: user.id }).find();
}

// ✅ 使用预加载
const users = orm.query(User)
  .with('orders')
  .find();

// 直接访问已加载的关联数据
for (const user of users) {
  console.log(user.orders?.length);
}

最佳实践

  1. 合理设计关联结构 - 避免过深的嵌套
  2. 选择合适的加载策略 - 根据使用场景选择预加载或延迟加载
  3. 谨慎使用级联删除 - 避免意外删除重要数据
  4. 注意外键命名规范 - @HasOne/@HasMany 使用数据库列名,@BelongsTo 使用属性名

开始探索 IBest ORM 的强大关联功能,构建高效的数据访问层!