sqlite SQL删除一对一关系行

vyu0f0g1  于 2023-10-23  发布在  SQLite
关注(0)|答案(2)|浏览(154)

我有这两个实体:

export class MyEntity {
    ...

    @OneToOne(() => Item, (item) => item.entity)
    item: Item:

    @ManyToOne(() => User, (user) => user.createdMyEntities)
    createdBy: User;

    ...
}

export class Item {
    ...

    @OneToOne(() => MyEntity, (myEntity) => myEntity.item)
    @JoinColumn()
    entity: MyEntity;

    ...
}

我想删除MyEntity中的一行,但这将给予一个SQLITE_CONSTRAINT: FOREIGN KEY constraint failed错误。我不想同时删除Item,我只想删除MyEntity并删除与它的关系。
我怎么能这么做呢?

jmp7cifd

jmp7cifd1#

删除一对一关系可能会很棘手,因为有时它会给予Foreign Key错误,您可以使用多个级联选项来查看是否有任何工作。另一个可行的解决方法是选择()您想要删除的行并基于外键连接,然后对于出现的行,您可以简单地更新这些外键列以删除关系,最后您可以删除所需的行。我附上示例代码供您参考:

// Assuming you have a repository or a database connection instance
const myEntityRepository = /* Initialize your repository or connection */ ;

// Find the MyEntity instance you want to delete
const myEntityToDelete = await myEntityRepository.findOne( /* your conditions here */ );

if (myEntityToDelete) {
  // Remove the association between MyEntity and Item
  myEntityToDelete.item = null;

  // Save the changes to update the entity without the association
  await myEntityRepository.save(myEntityToDelete);

  // Now you can safely delete the MyEntity instance
  await myEntityRepository.remove(myEntityToDelete);
}
bogh5gae

bogh5gae2#

在@OneTOOne关系定义中,将cascade设置为persistent,并仅合并。

相关问题