【问题标题】:Saving a list of Entity using TypeORM使用 TypeORM 保存实体列表
【发布时间】:2019-04-03 11:21:16
【问题描述】:

我正在使用Repository typeorm 类来处理我的 Postgres 数据库。

我的问题是在调用feedRepository.save(feeds) 时,将feedRepository 声明为feedRepository: Repository<Feed>feeds 的某些元素可能对插入无效。如何强制 typeorm 跳过无效实体并继续插入有效实体?

P/S:我有特殊的原因不使用for loop来一一插入数据。

【问题讨论】:

    标签: postgresql typescript typeorm


    【解决方案1】:

    您可以按照文档中的说明使用要在存储库中保存为参数的实体列表一次保存多个实体:

    /**
     * Saves all given entities in the database.
     * If entities do not exist in the database then inserts, otherwise updates.
     */
    save<T extends DeepPartial<Entity>>(entities: T[], options?: SaveOptions): Promise<T[]>;
    /**
     * Saves a given entity in the database.
     * If entity does not exist in the database then inserts, otherwise updates.
     */
    save<T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise<T>;
    

    您应该首先使用验证工具来验证您的实体,例如 class-validator https://github.com/typestack/class-validator

    您还可以在您的实体类中实现一个方法isValid(): boolean,您可以使用该方法来确定您的数据是否正确,然后根据此功能过滤列表。

    您只会花费计算时间来使用验证器检查您的实体,因此它应该非常快,比处理来自数据库的异常或过度调整 typeorm 好得多。

    【讨论】:

    • 在返回 save>(entities: T[], options?: SaveOptions): Promise 的结果时 typeORM 是否保证实体的顺序??
    猜你喜欢
    • 2020-09-18
    • 2021-08-05
    • 2021-08-08
    • 1970-01-01
    • 2022-08-18
    • 2020-10-02
    • 1970-01-01
    • 2018-09-10
    • 2021-10-06
    相关资源
    最近更新 更多