【发布时间】:2021-09-11 08:01:42
【问题描述】:
我正在构建一个简单的发票 API。
我有两个类Invoice和Address,Invoice有两个与Address相关的字段:senderAddress和clientAddress
我希望能够删除 Invoice 并自动删除 senderAddress 和 clientAddress。
我尝试了很多东西,比如将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