TypeORM 无法删除具有 ManyToOne / OneToMany 关系的行
TypeORM cannot delete row with ManyToOne / OneToMany relation
我现在遇到这个问题,我不知道如何诚实地解决。我已经在这上面花了好几个小时,但找不到解决方案。我在 Azure 上使用 MS-SQL。
我设置实体的方式如下:
- 客户和访问:OneToMany(主要)
- 访问量和客户:ManyToOne(反向)
我正在软删除我的客户,这样无论用户是否想具体查看客户数据,都可以检索访问信息。数据仍在使用关系正确解析。这也是为什么我不想在这里使用“级联删除”的原因。
但是,由于我想完全删除访问(而不是像客户那样软删除),所以我面临着可能与外键约束有关的问题(不确定,因为我没有从 TypeORM 得到任何错误输出)。 DeleteResult.affected 属性 但是 returns 0,这也是我在 DataGrip 查询中看到的,我在其中检查了实际的 table 数据。
同样重要的是,我可以使用如下简单的 SQL 语句手动删除行:
DELETE FROM visits
WHERE uuid = 'f0ea300d-...-656a'
我的实体是这样设置的(留下了不重要的信息):
@Entity({ name: 'customers' })
export class Customer {
@PrimaryColumn()
uuid: string
@OneToMany(() => Visit, (visit) => visit.customer)
visits?: Visit[]
}
@Entity({ name: 'visits' })
export class Visit {
@PrimaryColumn()
uuid: string
@ManyToOne(() => Customer, (customer) => customer.visits)
customer: Customer
}
我的 GraphQL 解析器:
@Mutation(() => Boolean)
async deleteVisitsByUuid(
@Arg('uuid') uuid: string,
@Ctx() { conn }: AppContext,
): Promise<boolean> {
const repo = conn.getRepository(Customer)
const result = await repo.delete(uuid)
const affected = result.affected
if (affected === undefined || affected == null) {
return false
} else {
return affected > 0
}
}
问题是 conn.getRepository(客户)。我已将其替换为 conn.getRepository(Visit).
我现在遇到这个问题,我不知道如何诚实地解决。我已经在这上面花了好几个小时,但找不到解决方案。我在 Azure 上使用 MS-SQL。
我设置实体的方式如下:
- 客户和访问:OneToMany(主要)
- 访问量和客户:ManyToOne(反向)
我正在软删除我的客户,这样无论用户是否想具体查看客户数据,都可以检索访问信息。数据仍在使用关系正确解析。这也是为什么我不想在这里使用“级联删除”的原因。
但是,由于我想完全删除访问(而不是像客户那样软删除),所以我面临着可能与外键约束有关的问题(不确定,因为我没有从 TypeORM 得到任何错误输出)。 DeleteResult.affected 属性 但是 returns 0,这也是我在 DataGrip 查询中看到的,我在其中检查了实际的 table 数据。
同样重要的是,我可以使用如下简单的 SQL 语句手动删除行:
DELETE FROM visits
WHERE uuid = 'f0ea300d-...-656a'
我的实体是这样设置的(留下了不重要的信息):
@Entity({ name: 'customers' })
export class Customer {
@PrimaryColumn()
uuid: string
@OneToMany(() => Visit, (visit) => visit.customer)
visits?: Visit[]
}
@Entity({ name: 'visits' })
export class Visit {
@PrimaryColumn()
uuid: string
@ManyToOne(() => Customer, (customer) => customer.visits)
customer: Customer
}
我的 GraphQL 解析器:
@Mutation(() => Boolean)
async deleteVisitsByUuid(
@Arg('uuid') uuid: string,
@Ctx() { conn }: AppContext,
): Promise<boolean> {
const repo = conn.getRepository(Customer)
const result = await repo.delete(uuid)
const affected = result.affected
if (affected === undefined || affected == null) {
return false
} else {
return affected > 0
}
}
问题是 conn.getRepository(客户)。我已将其替换为 conn.getRepository(Visit).