nestjs - 使用 TypeOrm Lazy Type 时哪个代码是正确的?
问题描述
TypeOrm 官方文档说在使用 Lazy Type 时使用 Promise。但我没有使用那种方法,因为我有 Lazy 选项。这两种方法有什么区别?
@Entity('COMPANY')
export class Company extends TimeStamped {
@PrimaryGeneratedColumn('increment')
companyId: number;
@Column({ type: 'varchar' })
companyName: string;
@OneToMany(() => Employee, (employee) => employee.company, {
onDelete: 'CASCADE',
lazy: true
})
employee: Employee[];
}
@Entity('COMPANY')
export class Company extends TimeStamped {
@PrimaryGeneratedColumn('increment')
companyId: number;
@Column({ type: 'varchar' })
companyName: string;
@OneToMany(() => Employee, (employee) => employee.company, {
onDelete: 'CASCADE'
})
employee: Promise<Employee[]>;
}
解决方案
如果您检查Typeorm 关系选项代码:
export interface RelationOptions {
...
/**
* Set this relation to be lazy. Note: lazy relations are promises.
* When you call them they return a promise which resolves relation
* result then. If your property's type is Promise then this relation
* is set to lazy automatically.
*/
lazy?: boolean;
...
}
在您的第一个示例中,当您想要的值时,employee
您必须编写如下内容:
const employees = await company.employee;
但是如果开发人员稍后检查代码,他可能会感到困惑,为什么await
一个类的属性不是 Promise。
在您的第二个示例中,您将编写与上面相同的代码。但是现在,任何开发人员都会知道该属性是一个承诺,因此他们必须这样做await
(这也将有助于 ESLint)。
因此,理想情况下,您应该使用第二个示例或以下我认为对开发人员更直观的示例:
@OneToMany(() => Employee, (employee) => employee.company, {
onDelete: 'CASCADE',
lazy: true
})
employee: Promise<Employee[]>;
推荐阅读
- javascript - 如何制作返回错误消息的通用验证函数?
- excel - 如何循环两列并将结果放入一列?
- php - 我如何在我的三个模型之间建立关系,其中 Distributor 和 Product 模型与 Distributorproduct 模型直接相关
- gatsby - 如何在 GatsbyJS 中构建和集成联系表单
- angular - 角度路由教程问题
- webhooks - Apollo 是否有可能从 webhook 宁静的第三方那里收听
- php - 如何将 Laravel 与 Nuxt js 集成
- caching - 单击时缓存整个 PWA
- electron - Windows Defender SmartScreen 和电子应用程序
- react-native - 反应原生 rn_bottom_drawer 的动态高度