admin管理员组

文章数量:1398832

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?

本文标签: typescriptTypeORM doesn39t detect moved entititesStack Overflow