最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - TypeORM doesn't detect moved entitites - Stack Overflow

programmeradmin6浏览0评论

I have an entity in mysql database that point to itself with many-to-one relationship. The example looks like this (max depth is 3 and is checked before accessing database):

{
    id: 1,
    name: "Root",
    children: [
        {
            id: 2,
            name: "Child 1",
            children: [
                {
                    id: 3,
                    name: "Grandchild 1",
                    children: []
                }
            ]
        },
        {
            id: 4,
            name: "Child 2",
            children: []
        }
    ]
}

However, when I load it from the database, move the entity with id = 3 to the parent with id = 4 and save, the moved entity gets deleted. The modified entity that I am trying to save looks like this:

{
    id: 1,
    name: "Root",
    children: [
        {
            id: 2,
            name: "Child 1",
            children: []
        },
        {
            id: 4,
            name: "Child 2",
            children: [
                {
                    id: 3,
                    name: "Grandchild 1",
                    children: []
                }
            ]
        }
    ]
}

The cascade option is true on children property in the entity in OneToMany relation

// For finding an entity I use 
repository.findOne({ 
    where: { id }, 
    relations: ['children', 'children.children']
}) 

//and for saving I use 
repository.save(entity).

After some debugging I found the exact queries the TypeORM executes. Especially, it executes 2 queries: The first one modifies the FK of the moved entity, so everything should be fine. But the second one sets FK to null.

It seems like TypeORM compares the old and the new one and does not understand that it was moved. It thinks, the entity was added to another parent, so it changes the parent. And then it removed it because it is no longer present in the old parent.

Is there a way to fix this?

发布评论

评论列表(0)

  1. 暂无评论