关联关系概览
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);详细文档
基础概念
- 基础关联 - 关联类型和配置
查询策略
数据操作
- 级联操作 - 自动处理关联数据
具体关联类型
- Has One - 一对一关联
- Has Many - 一对多关联
- Belongs To - 多对一关联
- Many To Many - 多对多关联
性能优化
选择合适的加载策略
| 场景 | 推荐策略 | 原因 |
|---|---|---|
| 列表页面 | 预加载 | 减少查询次数 |
| 详情页面 | 延迟加载 | 按需加载数据 |
| 批量操作 | 预加载 | 避免 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);
}最佳实践
- 合理设计关联结构 - 避免过深的嵌套
- 选择合适的加载策略 - 根据使用场景选择预加载或延迟加载
- 谨慎使用级联删除 - 避免意外删除重要数据
- 注意外键命名规范 -
@HasOne/@HasMany使用数据库列名,@BelongsTo使用属性名
开始探索 IBest ORM 的强大关联功能,构建高效的数据访问层!