SoftDelete:无法设置标志deletedBy、deletedAt

问题描述 投票:0回答:2

当我删除具有

softDelete
列的实体时,
deletedAt
deletedBy
为空或未设置。

如果我尝试

softRemove
,它只会设置
deletedAt
标志。

以下是实体的一些代码:

@DeleteDateColumn({ name: 'deleted_at'})
deletedAt: Date;

@Column({ type: 'varchar', name: 'deleted_by', nullable: true })
deletedBy: string;

服务方面:

public async delete(id: string): Promise<void> {
    const talent: Talent = await this.talentRepository.findOne(id);

    if (!talent) throw new NotFoundException(`Talent with ID ${id} Not Found`);

    talent.deletedBy = "John Doe";

    await this.talentRepository.softDelete(talent);
}

如果我登录此服务,参数

deletedBy
设置为“John Doe”,但数据库为空。

next.js typeorm
2个回答
7
投票

软删除只会更新

deletedAt
列。如果您想更新
deletedBy
,您应该将其作为更新查询单独执行。

来自源代码文档:

软删除:

    /**
     * Records the delete date of entities by a given condition(s).
     * Unlike save method executes a primitive operation without cascades, relations and other operations included.
     * Executes fast and efficient DELETE query.
     * Does not check if entity exist in the database.
     * Condition(s) cannot be empty.
     */

软删除:

   /**
     * Records the delete date of all given entities.
     */

可选的解决方案可以是:

public async delete(id: string): Promise<void> {
    const talent: Talent = await this.talentRepository.findOne(id);

    if (!talent) throw new NotFoundException(`Talent with ID ${id} Not Found`);

    talent.deletedBy = "John Doe";

    await this.talentRepository.save(talent);
    await this.talentRepository.softDelete(talent);
}

或者在交易中:

    public async delete(id: string): Promise<void> {
        const talent: Talent = await this.talentRepository.findOne(id);

        if (!talent) throw new NotFoundException(`Talent with ID ${id} Not Found`);

        talent.deletedBy = "John Doe";

        await this.talentRepository
            .manager
            .transaction(async em => {
                await em.save(Talent, talent);
                return em.softDelete(Talent, talent);
            });
    }

0
投票

当您使用

deletedAt
 时,TypeORM 仅更新 
softDelete()

作为其他答案的优化版本,您可以使用此方法通过更少的数据库调用(2)和更少的行数来更新

deletedBy
或您添加的任何其他自定义列:

public async delete(id: string): Promise<void> {
    const talent: Talent = await this.talentRepository.createQueryBuilder().update(Talent).set({ deletedBy: "John Doe" }).where('id = :id', { id }).execute();

    if (!talent) throw new NotFoundException(`Talent with ID ${id} Not Found`);

    await this.talentRepository.softDelete(talent);
}

此代码片段将运行两个数据库更新查询。

© www.soinside.com 2019 - 2024. All rights reserved.