【问题标题】:TypeORM OneToOne relationship cascade delete not workingTypeORM OneToOne 关系级联删除不起作用
【发布时间】:2021-09-11 08:01:42
【问题描述】:

我正在构建一个简单的发票 API。

我有两个类InvoiceAddressInvoice有两个与Address相关的字段:senderAddressclientAddress

我希望能够删除 Invoice 并自动删除 senderAddressclientAddress

我尝试了很多东西,比如将onDelete and Cascade 添加到Address OneToOne,它们不会被删除。

export class Invoice {
    @OneToOne(() => Address, (senderAddress) => senderAddress.invoice, {
        cascade: true,
        onDelete: 'CASCADE',
        eager: true,
    })
    @JoinColumn()
    senderAddress: Address;

    @OneToOne(() => Address, (clientAddress) => clientAddress.invoice, {
        cascade: true,
        onDelete: 'CASCADE',
        eager: true,
    })
    @JoinColumn()
    clientAddress: Address;
}
export class Address {
    @OneToOne(() => Invoice)
    invoice: Invoice;
}

这就是我删除Invoice的方式

async remove(id: number): Promise<Invoice> {
    const invoice = await this.invoiceRepository.findOne(id);
    if (!invoice)
        throw new HttpException('Invoice not found', HttpStatus.NOT_FOUND);

    return await this.invoiceRepository.remove(invoice);
}

这是在生成迁移时生成的:

public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `CREATE TABLE \`invoices-app\`.\`invoice\` (\`id\` int NOT NULL AUTO_INCREMENT, \`createdAt\` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), \`paymentDue\` datetime NOT NULL, \`description\` varchar(255) NOT NULL, \`paymentTerms\` int NOT NULL, \`clientName\` varchar(255) NOT NULL, \`clientEmail\` varchar(255) NOT NULL, \`status\` varchar(255) NOT NULL, \`total\` int NOT NULL, \`senderAddressId\` int NULL, \`clientAddressId\` int NULL, \`userId\` int NULL, UNIQUE INDEX \`REL_39d5b5b8c9b14ee7d3a28ec6be\` (\`senderAddressId\`), UNIQUE INDEX \`REL_2d58047fd2c36422476e1e1fd3\` (\`clientAddressId\`), PRIMARY KEY (\`id\`)) ENGINE=InnoDB`,
        );

        await queryRunner.query(
            `CREATE TABLE \`invoices-app\`.\`address\` (\`id\` int NOT NULL AUTO_INCREMENT, \`street\` varchar(255) NOT NULL, \`city\` varchar(255) NOT NULL, \`postCode\` varchar(255) NOT NULL, \`country\` varchar(255) NOT NULL, PRIMARY KEY (\`id\`)) ENGINE=InnoDB`,
        );

        await queryRunner.query(
            `ALTER TABLE \`invoices-app\`.\`invoice\` ADD CONSTRAINT \`FK_39d5b5b8c9b14ee7d3a28ec6be3\` FOREIGN KEY (\`senderAddressId\`) REFERENCES \`invoices-app\`.\`address\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION`,
        );

        await queryRunner.query(
            `ALTER TABLE \`invoices-app\`.\`invoice\` ADD CONSTRAINT \`FK_2d58047fd2c36422476e1e1fd36\` FOREIGN KEY (\`clientAddressId\`) REFERENCES \`invoices-app\`.\`address\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION`,
        );
}

这是我的整个 ER 图

【问题讨论】:

    标签: javascript nestjs typeorm


    【解决方案1】:

    您需要在senderAddressclientAddress 上指定反面作为第二个参数,如下所示:

    export class Invoice {
        @OneToOne(() => Address, 
         senderAddress => senderAddress.invoice, // inverse side
         {
            cascade: ['insert'],
            onDelete: 'CASCADE',
            eager: true,
        })
        @JoinColumn()
        senderAddress: Address;
    
        @OneToOne(() => Address, 
         clientAddress => clientAddress.invoice, // inverse side
         {
            cascade: ['insert'],
            onDelete: 'CASCADE',
            eager: true,
        })
        @JoinColumn()
        clientAddress: Address;
    }
    

    【讨论】:

    • 谢谢先生,但他们仍然没有被删除
    • @H3lltronik 您可能需要再次执行数据库迁移 - 假设您让 TypeORM 使用注释自动生成和修改数据库。
    • 再次感谢您,先生,我更新了我的帖子。我正在使用synchronize: true,然后我将其更改为false并使用了迁移,但它也没有工作,但我看到了生成代码,它在它应该工作的约束中添加了ON DELETE CASCADE,对吧?你能看看吗?
    • @H3lltronik synchronize: true 通常非常适合开发,但不适合生产。在这种情况下可能不会考虑我发布的两个小更改,因此您最终会摆弄数据库本身......
    • @H3lltronik 您创建的迁移看起来不错。应该工作,是的。您可能希望在 up 方法中的事务中运行这些查询,例如return queryRunner.connection.transaction(async (em: EntityManager) =&gt; Promise.all([em.query('sql 1...'), em.query('sql 2...')]));
    猜你喜欢
    • 2021-01-01
    • 2014-07-24
    • 2021-06-10
    • 2016-12-13
    • 2011-10-21
    • 1970-01-01
    • 2013-06-22
    • 2013-03-03
    相关资源
    最近更新 更多