typeorm - 在 TypeOrm 中,OneToMany 和 ManyToOne 的默认获取类型是什么?
问题描述
Typeorm 的官方文档指出,如果使用 Lazy,则必须使用 Promise。如果不承诺,默认的获取类型会是急切加载吗?但是,我检查了一下,它似乎正在加载 Lazy,而不是 Eager。JPA 的默认音高类型如下:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
TypeOrm 的默认 fetch 类型是否相同?
解决方案
TLDR:既不是lazy
也不是eager
。
如果您检查Typeorm 关系选项代码:
export interface RelationOptions {
...
/**
* Set this relation to be lazy. Note: lazy relations are promises. When you call them they return promise
* which resolve relation result then. If your property's type is Promise then this relation is set to lazy automatically.
*/
lazy?: boolean;
/**
* Set this relation to be eager.
* Eager relations are always loaded automatically when relation's owner entity is loaded using find* methods.
* Only using QueryBuilder prevents loading eager relations.
* Eager flag cannot be set from both sides of relation - you can eager load only one side of the relationship.
*/
eager?: boolean;
...
}
您可以看到 Typeorm 默认情况下不会为任何类型的关系加载关系。基本上,既不是lazy
也不是eager
。
如果您既不设置lazy
也不设置eager
,它根本不会加载关系,除非您在find
选项中或在QueryBuilder
.
See the below example from Typeorm Documentation for find
:
const user = userRepository.find({
where: {
name: "John",
},
relations: ["project"],
});
// Think user has a one-to-many relationship with projects, then:
// const projects = user.projects;
If you specify lazy
or eager
then you don't need to specify it in find
options. But you will still have to specify the join condition when using QueryBuilder
.
For lazy
:
const user = userRepository.find({
where: {
name: "John",
}
});
// Need await for `lazy`:
// const projects = await user.projects;
For eager
:
const user = userRepository.find({
where: {
name: "John",
}
});
// No await for `eager`:
// const projects = user.projects;
Hope this helps. Cheers !!!
推荐阅读
- python - 如何在 tkinter 窗口打开时运行 while 循环?
- r - 解决 R 中函数名称冲突的最佳方法是什么?
- php - 为什么这个 jQuery 函数在某些浏览器上部分工作?
- xgboost - 使用 XgBoostClassifier 预测 Xgboost DMatrix 对象
- keras - 在 Keras 中使用 LSTM 获取单词用于文本分类的概率
- python - 如何每 3 小时迭代一次 for 循环,总共 7 天
- java - Spring boot rest在注册时设置用户默认配置文件图像
- date - 这种表示日期的二进制格式是什么?
- performance - 气流 - 装满 DagBag 真的很慢
- jsonschema - 使用 ajv json 模式验证器的用户友好错误消息