如何使用Typeorm删除多对多的关系数据?

问题描述 投票:0回答:3

我想要做的是,当我删除类别时,我想自动删除相关的待办事项。他们有多对多的关系

类别实体

@Entity('categories')
export class Category extends BaseEntity{
    @PrimaryColumn({type: 'bigint'})
    id:string;

    @Column()
    name:string;

    @ManyToMany(
        ()=>TodoItem, 
        todoItem => todoItem.categories
        ,{onDelete:"CASCADE"}
    ) 
    @JoinTable({
        name:"categories_todos",
        joinColumn:{
            name:"categories", 
            referencedColumnName:"id"
        },
        inverseJoinColumn:{
            name:"todos",
            referencedColumnName:"id"
        }
    })    
    todos:TodoItem[]

    @ManyToOne(
        ()=>User,
        user=>user.categoires
    )
    @JoinColumn({
        name: 'user_id'
    })
    user:User
}

Todo 实体

@Entity('todoItem')
export class TodoItem extends BaseEntity{
    @PrimaryColumn()
    id:string;
    @Column()
    completed:boolean;
    
    @Column()
    title: string; 


    @ManyToMany(
        ()=>Category,
        category => category.todos
    )
    categories:Category[]

   

}

这是我的删除类别 API

router.delete('/api/category/:categoryId',async(req:express.Request,res:express.Response)=>{
    const { categoryId } = req.params
    const category = await Category.findOne(categoryId)
    if(!category){
        return res.status(404).json({msg:"category not found"})
    }
    await Category.delete(category)
    return res.status(200).json(category) 
});

我尝试了 cascade:trueonDelete:"CASCADE" ,但它不起作用,我想知道问题是什么,下面是我的实体和删除 API。

express typeorm
3个回答
2
投票

删除

category
不会删除其包含的任何
todoItem
实体。相反,
cascade
只会从
category_todos_todoItem
表(由TypeORM自动创建)中删除关系。

要删除

todoItem
中的每个
category
,请循环遍历
category.todos
并手动删除每个
todoItem

category.todos.forEach( async (todoItem) => await TodoItem.delete(todoItem.id) );

您也可以尝试使用 Subscriber Class

自动执行此操作

注意:如果您有外键限制关系,您将遇到错误。在这种情况下,请使用 query

todoItem
中删除所有出现的
category_todos_todoItem
。然后你就可以删除
todoItem


1
投票

delete
方法很简单,但不会成功:

/**
 * Deletes entities by a given criteria.
 * Unlike save method executes a primitive operation without cascades, relations and other operations included.
 * Executes fast and efficient DELETE query.
 * Does not check if entity exist in the database.
 */

你可以尝试使用

remove


0
投票

迟到的答案,但这对我有用

const instance = await this.categoryRepository.findOneBy({ id });
Object.assign(instance, { todos: [] });
await this.categoryRepository.save(instance);
return await this.categoryRepository.delete(id);
© www.soinside.com 2019 - 2024. All rights reserved.