传播
默认情况下,MikroORM 会将对双向关系一侧所做的所有更改传播到另一侧,使它们保持同步。这适用于所有关系,包括 M:1 和 1:1。作为发现过程的一部分,所有 M:1 和 1:1 属性都被重新定义为 getter/setter。
¥By default, MikroORM will propagate all changes made to one side of bidirectional relations to the other side, keeping them in sync. This works for all relations, including M:1 and 1:1. As part of the discovery process, all M:1 and 1:1 properties are re-defined as getter/setter.
const author = new Author(...);
const book = new Book(...);
book.author = author;
console.log(author.books.contains(book)); // true
通过修改实体类原型,也支持通过构造函数创建的新实体的传播,但当启用 useDefineForClassFields
TypeScript 编译器标志时,此技术会失败(当针对 ES2022
或更高版本时为真)。你可以通过在实体定义中使用 declare
关键字或通过 em.create()
创建实体实例来解决这个问题,这将确保启用传播。
¥Propagation on new entities you create via constructor is supported too, by modifying the entity class prototype, but this technique fails when useDefineForClassFields
TypeScript compiler flag is enabled (which is true when targeting ES2022
or higher). You can get around this by using declare
keyword in your entity definition, or by creating entity instances via em.create()
, which will ensure the propagation is enabled.
Collection 的 add() 和 remove() 操作的传播
¥Propagation of Collection's add() and remove() operations
当你使用 Collection.add()
方法之一时,该项目将添加到给定的集合中,并且此操作也会传播到其对应项。
¥When you use one of Collection.add()
method, the item is added to given collection, and this action is also propagated to its counterpart.
// one to many
const author = new Author(...);
const book = new Book(...);
author.books.add(book);
console.log(book.author); // author will be set thanks to the propagation
对于 M:N,这可以双向工作,无论是从拥有方还是从反向方。
¥For M:N this works in both ways, either from owning side, or from inverse side.
// many to many works both from owning side and from inverse side
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
两侧的集合都必须初始化,否则传播将不起作用。
¥Collections on both sides have to be initialized, otherwise propagation won't work.
尽管这种传播也适用于 M:N 逆向侧,但你应该始终使用拥有侧来操作集合。
¥Although this propagation works also for M:N inverse side, you should always use owning side to manipulate the collection.
同样适用于 Collection.remove()
。
¥Same applies for Collection.remove()
.