SoftDelete:无法设置标志deletedBy、deletedAt

cro*_*rot 2 typeorm next.js

当我删除带有softDelete列的实体deletedAt并且deletedBy为空或未设置时。

如果我尝试softRemove,它只会设置deletedAt标志。

以下是实体的一些代码:

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

@Column({ type: 'varchar', name: 'deleted_by', nullable: true })
deletedBy: string;
Run Code Online (Sandbox Code Playgroud)

对于服务:

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);
}
Run Code Online (Sandbox Code Playgroud)

如果我登录此服务,参数deletedBy将设置为“John Doe”,但数据库为空。

noa*_*ner 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.
     */
Run Code Online (Sandbox Code Playgroud)

软删除:

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

Run Code Online (Sandbox Code Playgroud)

可选的解决方案可以是:

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);
}

Run Code Online (Sandbox Code Playgroud)

或者在事务中:

    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);
            });
    }
Run Code Online (Sandbox Code Playgroud)