集合
OneToMany 与 ManyToMany 属性被存放在一个 Collection 包装器中。
使用集合
Collection 类实现了迭代器协议,因此你可以用 for of 循环遍历它。你也可以按索引访问元素(例如 author.books[0]),但这种访问是只读的,并且不会检查集合是否已初始化。
const author = await em.findOne(Author, '...', { populate: ['books'] });
for (const book of author.books) {
console.log(book.title);
}
// 数组下标访问同样可用(只读)
console.log(author.books[0]); // Book类型安全的 $ 访问
当集合被 populate 时,MikroORM 会把它类型化为 LoadedCollection,它暴露了一个 $ 访问器(以及别名 get())。这为你提供了类型安全的集合访问方式,TypeScript 知道该集合已初始化:
const author = await em.findOne(Author, '...', { populate: ['books'] });
// `author.books.$` 的类型是 `Collection<Book>` —— TypeScript 知道它已加载
for (const book of author.books.$) {
console.log(book.title);
}如果没有 populate 提示,访问 $ 会产生编译错误,从而避免你误用一个尚未初始化的集合:
const author = await em.findOne(Author, '...');
// TS 错误:类型 'Collection<Book>' 上不存在属性 '$'
for (const book of author.books.$) { ... }你也可以在函数签名中使用 Loaded 类型来要求集合已被 populate:
function listBookTitles(author: Loaded<Author, 'books'>): string[] {
// 类型安全 —— books 保证已加载
return author.books.$.map(book => book.title);
}关于 Loaded、Ref 与 $ 访问器的完整文档,请参见类型安全关系指南。
加载集合
在操作集合中的元素之前,集合必须先被初始化。有几种加载集合的方式:
// 1. 查询时 populate
const author = await em.findOne(Author, '...', { populate: ['books'] });
// 2. load() —— 若尚未加载则初始化集合(已初始化时为空操作)
await author.books.load();
// 3. loadItems() —— 与 load() 相同,但直接以数组形式返回元素
const books = await author.books.loadItems(); // Book[]
// 4. init() —— 总是从数据库重新加载,即使已初始化
await author.books.init();不加载即可获取数量
使用 loadCount() 可以在不加载实体的情况下从数据库获取元素数量。结果会被缓存 —— 传入 { refresh: true } 可强制重新加载,传入 where 条件可统计子集(不缓存)。若需要不缓存的版本,请直接使用 count()。使用dataloader 时,传入 { dataloader: true } 可将多次计数查询合并为一批:
const author = await em.findOne(Author, '...');
const count = await author.books.loadCount(); // SELECT COUNT(*) ...
const count2 = await author.books.loadCount(); // 命中缓存,不发起查询
const count3 = await author.books.loadCount({ refresh: true }); // 强制重新加载
const activeCount = await author.books.loadCount({ where: { active: true } }); // 条件统计,不缓存
const count4 = await author.books.loadCount({ dataloader: true }); // 与其他 loadCount 调用合并成批添加与移除元素
使用 add() 添加元素,使用 remove() 移除元素。两者都返回实际被添加/移除的元素数量(重复项会被忽略):
const added = author.books.add(book1, book2); // 返回 2
const added2 = author.books.add(book1); // 返回 0(已在集合中)
const removed = author.books.remove(book1); // 返回 1remove() 还接受一个断言回调,用于移除满足条件的元素:
// 移除所有标题带有特定前缀的书
const removed = author.books.remove(book => book.title.startsWith('Draft:'));使用 set() 可替换整个集合的内容,使用 removeAll() 可清空集合:
author.books.set([book1, book2]); // 替换所有元素
author.books.removeAll(); // 移除所有元素从集合中移除元素
从集合中移除元素并不一定意味着删除目标实体,它表示你正在断开这层关系 —— 是从集合中移除元素,而不是从数据库中移除实体 —— Collection.remove() 与 em.remove() 并不相同。当你使用 em.assign() 更新实体时,也可以从集合中移除/断开实体,它们不会自动从数据库中被删除。如果你想通过从集合中移除来删除实体,需要启用 orphanRemoval: true,它会告诉 ORM 你不希望存在孤儿实体,因此这些实体应当被移除。另请查阅孤儿移除相关文档。
检查集合状态
author.books.contains(book); // 元素在集合中时为 true
author.books.count(); // 元素数量(等同于 author.books.length)
author.books.isEmpty(); // 没有任何元素时为 true
author.books.isInitialized(); // 集合已加载时为 true
author.books.isDirty(); // 集合自上次 flush 以来被修改过时为 true取出元素
author.books.getItems(); // T[] —— 未初始化时抛出异常
author.books.getItems(false); // T[] —— 不检查初始化状态直接返回元素
author.books.toArray(); // EntityDTO<T>[] —— 序列化后的 DTO,修改它们不会影响实体
author.books.getIdentifiers(); // Primary<T>[] —— 主键数组
author.books.slice(0, 5); // T[] —— 元素切片(与 Array.slice 一致)OneToMany 集合
OneToMany 集合是 ManyToOne 引用的反向端,需要通过 mappedBy 属性指向对方:
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author),
},
});
export const Author = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});@Entity()
export class Book {
@PrimaryKey()
id!: number;
@ManyToOne(() => Author)
author!: Author;
}
@Entity()
export class Author {
@PrimaryKey()
id!: number;
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
// 或通过选项对象
@OneToMany({ entity: () => Book, mappedBy: 'author' })
books2 = new Collection<Book>(this);
}@Entity()
export class Book {
@PrimaryKey()
id!: number;
@ManyToOne()
author!: Author;
}
@Entity()
export class Author {
@PrimaryKey()
id!: number;
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
}ManyToMany 集合
对于 ManyToMany,SQL 驱动会使用一张中间表(pivot table),其中持有对两端实体的引用。
与之不同的是,在 MongoDB 中 ManyToMany 关系不需要连接表。所有引用都以 ObjectId 数组的形式存储在拥有方实体上。
单向
单向 ManyToMany 关系只在其中一端定义,如果你只定义了 entity 属性,那么它会被视为拥有方:
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.manyToMany(Book),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);export const Author = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.manyToMany(Book),
},
});@ManyToMany(() => Book)
books = new Collection<Book>(this);
// 或通过选项对象显式标记为拥有方
@ManyToMany({ entity: () => Book, owner: true })
books2 = new Collection<Book>(this);@ManyToMany()
books = new Collection<Book>(this);双向
双向 ManyToMany 关系在两端都有定义,其中一端是拥有方(引用存储在这一端),通过 inversedBy 属性指向反向端:
// 拥有方
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
tags: () => p.manyToMany(BookTag).inversedBy('books'),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
// 反向端
const BookTagSchema = defineEntity({
name: 'BookTag',
properties: {
id: p.integer().primary(),
books: () => p.manyToMany(Book).mappedBy('tags'),
},
});
export class BookTag extends BookTagSchema.class {}
BookTagSchema.setClass(BookTag);// 拥有方
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
tags: () => p.manyToMany(BookTag).inversedBy('books'),
},
});
// 反向端
export const BookTag = defineEntity({
name: 'BookTag',
properties: {
id: p.integer().primary(),
books: () => p.manyToMany(Book).mappedBy('tags'),
},
});// 拥有方
@ManyToMany(() => BookTag, tag => tag.books, { owner: true })
tags = new Collection<BookTag>(this);
// 或通过选项对象
@ManyToMany({ entity: () => BookTag, inversedBy: 'books' })
tags = new Collection<BookTag>(this);
// 反向端
@ManyToMany(() => Book, book => book.tags)
books = new Collection<Book>(this);
// 或通过选项对象
@ManyToMany({ entity: () => Book, mappedBy: 'tags' })
books = new Collection<Book>(this);// 拥有方
@ManyToMany({ inversedBy: 'books' })
tags = new Collection<BookTag>(this);
// 反向端
@ManyToMany({ mappedBy: 'tags' })
books = new Collection<Book>(this);为中间表的连接列建立索引
生成的中间表的连接列是否被索引,取决于平台默认值(例如 SQLite 会为每个外键建立索引,PostgreSQL 则不会)。你可以通过 M:N 属性拥有方上的 index 选项来覆盖这一行为:
@ManyToMany({ entity: () => User, index: true })
users = new Collection<User>(this);使用 index: true 时,只有那些尚未被中间表复合主键的前导列覆盖的连接列才会额外建立索引 —— 对默认的中间表而言,这意味着只有反向连接列会被索引,而启用 fixedOrder 时两列都会被索引。拥有方连接列始终保持平台默认行为(因此在会为每个外键建索引的平台上,它依然会被索引)。你也可以传入字符串为索引命名(该名称作用于反向连接列),或传入 index: false 来禁用平台默认索引。
自定义中间表实体
默认情况下,底层会使用一个自动生成的中间表实体来表示中间表。你可以通过 pivotEntity 选项提供自己的实现。
该中间表实体必须恰好拥有两个 many-to-one 属性,其中第一个需要指向拥有方实体,第二个指向这个多对多关系的目标实体。
const OrderSchema = defineEntity({
name: 'Order',
properties: {
id: p.integer().primary(),
products: () => p.manyToMany(Product).pivotEntity(() => OrderItem),
},
});
export class Order extends OrderSchema.class {}
OrderSchema.setClass(Order);
const ProductSchema = defineEntity({
name: 'Product',
properties: {
id: p.integer().primary(),
orders: () => p.manyToMany(Order).mappedBy('products'),
},
});
export class Product extends ProductSchema.class {}
ProductSchema.setClass(Product);
const OrderItemSchema = defineEntity({
name: 'OrderItem',
properties: {
order: () => p.manyToOne(Order).primary(),
product: () => p.manyToOne(Product).primary(),
amount: p.integer().default(1),
},
});
export class OrderItem extends OrderItemSchema.class {}
OrderItemSchema.setClass(OrderItem);export const Order = defineEntity({
name: 'Order',
properties: {
id: p.integer().primary(),
products: () => p.manyToMany(Product).pivotEntity(() => OrderItem),
},
});
export const Product = defineEntity({
name: 'Product',
properties: {
id: p.integer().primary(),
orders: () => p.manyToMany(Order).mappedBy('products'),
},
});
export const OrderItem = defineEntity({
name: 'OrderItem',
properties: {
order: () => p.manyToOne(Order).primary(),
product: () => p.manyToOne(Product).primary(),
amount: p.integer().default(1),
},
});@Entity()
export class Order {
@PrimaryKey()
id!: number;
@ManyToMany({ entity: () => Product, pivotEntity: () => OrderItem })
products = new Collection<Product>(this);
}
@Entity()
export class Product {
@PrimaryKey()
id!: number;
@ManyToMany({ entity: () => Order, mappedBy: o => o.products })
orders = new Collection<Order>(this);
}
@Entity()
export class OrderItem {
@ManyToOne({ primary: true })
order: Order;
@ManyToOne({ primary: true })
product: Product;
@Property({ default: 1 })
amount!: number;
}@Entity()
export class Order {
@PrimaryKey()
id!: number;
@ManyToMany({ pivotEntity: () => OrderItem })
products = new Collection<Product>(this);
}
@Entity()
export class Product {
@PrimaryKey()
id!: number;
@ManyToMany({ mappedBy: 'products' })
orders = new Collection<Order>(this);
}
@Entity()
export class OrderItem {
@ManyToOne({ primary: true })
order: Order;
@ManyToOne({ primary: true })
product: Product;
@Property({ default: 1 })
amount!: number;
}对于双向 M:N 关系,只需在拥有方指定 pivotEntity 选项即可。你仍然需要通过 inversedBy 或 mappedBy 选项把两端关联起来。
如果你想向这样的 M:N 集合添加新元素,那么所有非外键属性都必须定义数据库层面的默认值。
或者,你也可以直接操作中间表实体:
// 创建新条目
const item = em.create(OrderItem, {
order: 123,
product: 321,
amount: 999,
});
await em.persist(item).flush();
// 或通过 delete 查询移除条目
await em.nativeDelete(OrderItem, { order: 123, product: 321 });你也可以像上例那样定义指向中间表实体的 1:m 属性,并用它来修改集合,同时把 M:N 属性用于更便捷的读取与过滤。
强制固定集合元素顺序
多对多集合并不要求拥有自增主键。
要保留集合的固定顺序,可以使用 fixedOrder: true 属性,它会改为按 id 列排序。Schema 生成器会把中间表转换为拥有自增主键 id。你也可以通过 fixedOrderColumn: 'order' 修改排序列名。
你还可以通过 orderBy: { ... } 属性指定默认排序。当完整 populate 集合(包含其元素)时会使用它,因为它按被引用实体的属性排序,而不是按中间表的列(fixedOrderColumn 才是)。另一方面,fixedOrder 用于维持元素的插入顺序,而不是按某个属性排序。
填充引用
有时你只想知道集合中包含哪些元素,而不关心这些元素的具体值。为此,你可以只用引用来填充集合:
const book1 = await em.findOne(Book, 1, { populate: ['tags:ref'] });
console.log(book1.tags.isInitialized()); // true
console.log(wrap(book1.tags[0]).isInitialized()); // false
// 或者改用 `init({ ref: true })`
const book2 = await em.findOne(Book, 1);
await book2.tags.init({ ref: true });
console.log(book2.tags.isInitialized()); // true
console.log(wrap(book2.tags[0]).isInitialized()); // falseCollection 的 add() 与 remove() 操作的传播
当你调用 Collection.add() 系列方法之一时,元素会被添加到给定集合中,这一操作同时也会传播到它的对应端。
// 一对多
const author = new Author(...);
const book = new Book(...);
author.books.add(book);
console.log(book.author); // 由于传播机制,author 会被自动设置对于 M:N,这在两个方向上都有效,无论从拥有方还是从反向端。
// 多对多从拥有方和反向端都有效
const book = new Book(...);
const tag = new BookTag(...);
book.tags.add(tag);
console.log(tag.books.contains(book)); // true
tag.books.add(book);
console.log(book.tags.contains(tag)); // true即使拥有方集合尚未初始化,向 M:N 关系反向端添加新元素的传播也依然生效。但对于 remove 操作的传播,两端仍都必须已初始化。
尽管这种传播在 M:N 反向端同样有效,你仍应始终使用拥有方来操作集合。
Collection.remove() 同理。
集合元素的过滤与排序
通过 collection.init() 初始化集合元素时,你既可以过滤集合,也可以对其元素排序:
await book.tags.init({
where: { active: true },
orderBy: { name: QueryOrder.DESC },
});切勿修改部分加载的集合。
实体级默认排序
你可以使用 @Entity({ orderBy: ... }) 在实体自身上定义默认 orderBy。在 populate 集合时,所有适用的排序规则会被合并,运行时 orderBy 优先级最高,其次是关系级 orderBy,最后是实体级 orderBy。
完整文档与示例请参见实体默认排序。
声明式部分加载
集合也可以只表示目标实体的一个子集:
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.oneToMany(Book).mappedBy('author'),
favoriteBooks: () => p.oneToMany(Book).mappedBy('author').where({ favorite: true }),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);export const Author = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.oneToMany(Book).mappedBy('author'),
favoriteBooks: () => p.oneToMany(Book).mappedBy('author').where({ favorite: true }),
},
});@Entity()
class Author {
@OneToMany(() => Book, b => b.author)
books = new Collection<Book>(this);
@OneToMany(() => Book, b => b.author, { where: { favorite: true } })
favoriteBooks = new Collection<Book>(this);
}@Entity()
class Author {
@OneToMany(() => Book, b => b.author)
books = new Collection<Book>(this);
@OneToMany(() => Book, b => b.author, { where: { favorite: true } })
favoriteBooks = new Collection<Book>(this);
}这同样适用于 M:N 关系。注意,如果你想声明多个映射到同一张中间表的关系,需要显式指定表名(或使用同一个中间表实体):
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
tags: () => p.manyToMany(BookTag),
popularTags: () => p.manyToMany(BookTag).pivotTable('book_tags').where({ popular: true }),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
tags: () => p.manyToMany(BookTag),
popularTags: () => p.manyToMany(BookTag).pivotTable('book_tags').where({ popular: true }),
},
});@Entity()
class Book {
@ManyToMany(() => BookTag)
tags = new Collection<BookTag>(this);
@ManyToMany({
entity: () => BookTag,
pivotTable: 'book_tags',
where: { popular: true },
})
popularTags = new Collection<BookTag>(this);
}@Entity()
class Book {
@ManyToMany()
tags = new Collection<BookTag>(this);
@ManyToMany({
entity: () => BookTag,
pivotTable: 'book_tags',
where: { popular: true },
})
popularTags = new Collection<BookTag>(this);
}过滤集合
集合提供了 matching 方法,用于从集合中切出一部分数据。默认情况下,它会基于查询返回实体列表。你可以使用 store 布尔参数把这份列表保存到集合元素中 —— 这会把集合标记为 readonly,add、remove 等方法会抛出异常。
const a = await em.findOneOrFail(Author, 1);
// 只加载元素列表
const books = await a.books.matching({ limit: 3, offset: 10, orderBy: { title: 'asc' } });
console.log(books); // [Book, Book, Book]
console.log(a.books.isInitialized()); // false
// 把元素存入集合
const tags = await books[0].tags.matching({
limit: 3,
offset: 5,
orderBy: { name: 'asc' },
store: true,
});
console.log(tags); // [BookTag, BookTag, BookTag]
console.log(books[0].tags.isInitialized()); // true
console.log(books[0].tags.getItems()); // [BookTag, BookTag, BookTag]集合辅助方法
Collection 类提供了若干类似数组的辅助方法,它们作用于已加载的元素。这些方法都要求集合已初始化 —— 否则会抛出异常。
map
将每个元素传入回调进行映射,与 Array.map() 一致:
const titles = author.books.map(book => book.title); // string[]filter
返回满足断言的元素,与 Array.filter() 一致。支持类型守卫:
const longBooks = author.books.filter(book => book.pageCount > 300); // Book[]find
返回第一个满足断言的元素,与 Array.find() 一致。支持类型守卫:
const firstLongBook = author.books.find(book => book.pageCount > 300); // Book | undefinedexists
若存在任何元素满足断言,则返回 true:
const hasLongBook = author.books.exists(book => book.pageCount > 300); // booleanreduce
把集合归约为单个值,与 Array.reduce() 一致:
const totalPages = author.books.reduce((sum, book) => sum + book.pageCount, 0); // numberindexBy
把集合转换为以给定属性为键的键值字典:
// 假设 `user.settings` 是 `Collection<Option>`
const settingsDictionary = user.settings.indexBy('key');
// Record<string, Option>第二个参数允许你映射为属性值而非目标实体:
const settingsDictionary = user.settings.indexBy('key', 'value');
// Record<string, string>