首页 > 解决方案 > 使用 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[]>;
}

标签: nestjstypeorm

解决方案


如果您检查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[]>;

推荐阅读