next.js - SoftDelete : Can't set flag deletedBy, deletedAt

标签 next.js typeorm

当我删除带有 softDelete 列的实体时,deletedAtdeletedBy 为空或未设置。

如果我尝试 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”,但数据库为空。

最佳答案

软删除只会更新 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(em => {
                await em.save(Talent, talent);
                return em.softDelete(Talent, talent);
            });
    }

关于next.js - SoftDelete : Can't set flag deletedBy, deletedAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65688600/

相关文章:

reactjs - 在 NextJS 中使用持久布局和高阶函数

javascript - 如何获取所有参数转义的原始 sql 查询字符串?

typescript - 是否可以使用 TypeOrm 从对象设置字段值?

reactjs - NextJS,在 getServerSideProps 中预加载 Redux 数据

reactjs - TypeError:在 Next.js 中使用 urql 客户端时无法读取未定义的属性(读取 'reduceRight' )

nestjs - 如何在 Nestjs DatabaseModule 中使用 ConfigService

postgresql - 使用 Between 查询 api Repository Typeorm 上的日期

sql - TypeORM 限制不起作用,无论设置多少限制,查询都会返回数组中的一个元素?

javascript - 无法从 POST 请求获取表单数据

javascript - React useState Hook 是附加值而不是覆盖