使用 TypeOrm Lazy Type 时,哪个代码是正确的?
Which code is correct when using 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 relation options code:
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;
但是如果开发人员稍后检查代码,他可能会感到困惑,为什么在 class 的 属性 上有一个 await
这不是一个承诺。
在您的秒示例中,您将编写与上面相同的代码。但是现在,任何开发人员都会知道 属性 是一个承诺,因此他们必须 await
(这也将有助于 ESLint)。
理想情况下,您应该使用第二个示例或以下我认为对开发人员更直观的示例:
@OneToMany(() => Employee, (employee) => employee.company, {
onDelete: 'CASCADE',
lazy: true
})
employee: Promise<Employee[]>;
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 relation options code:
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;
但是如果开发人员稍后检查代码,他可能会感到困惑,为什么在 class 的 属性 上有一个 await
这不是一个承诺。
在您的秒示例中,您将编写与上面相同的代码。但是现在,任何开发人员都会知道 属性 是一个承诺,因此他们必须 await
(这也将有助于 ESLint)。
理想情况下,您应该使用第二个示例或以下我认为对开发人员更直观的示例:
@OneToMany(() => Employee, (employee) => employee.company, {
onDelete: 'CASCADE',
lazy: true
})
employee: Promise<Employee[]>;