代码之家  ›  专栏  ›  技术社区  ›  Jonathan

使用TypeORM更新多对多关系

  •  1
  • Jonathan  · 技术社区  · 7 年前

    我在更新一个有多对多关系的实体时遇到问题,我很好奇我是否做错了什么,或者更具体地说,什么是正确的方法

    考虑以下实体。。。

    @Entity
    class Subject
      @PrimaryGeneratedColumn('uuid')
      id: string;
    
      @Column()
      name: string;
    
      @ManyToMany(() => Note, note => note.subjects)
      @JoinTable()
      notes: Note[];
    
      ...
    
    @Entity()
    export class Note {
      @PrimaryGeneratedColumn('uuid')
      id: string;
    
      @ManyToMany(() => Subject, (subject: Subject) => subject.notes)
      subjects: Subject[];
    

    在我的代码中,我找到了节点,然后尝试更新它,然后像这样保存。。。

    const note = await noteRepo.findOneOrFail(noteId);
    const foundSubjects = await subjectRepo.findByIds(Array.from(subjectIds));
    note.subjects = foundSubjects;
    noteRepo.save(note);
    

    但遗憾的是,这些主题并没有保存在笔记上。

    正确的方法是什么?

    谢谢

    2 回复  |  直到 7 年前
        1
  •  14
  •   Nestor Perez    7 年前

    在我的例子中,我试图更新一个现有的关系,但这给了我一个唯一的密钥冲突,因为该关系已经存在,所以我首先需要删除所有现有的关系,然后添加我更新的用户的关系:

    export const updateUser = async (user: User): Promise<User | undefined> => {
        /**
         * Get the actual relationships of that user.
         */
        const actualRelationships = await getRepository(User)
            .createQueryBuilder()
            .relation(User, 'roles')
            .of(user).loadMany();
    
        /**
         * Add new relationships of the user, and delete the old relationships.
         */
        await getRepository(User)
            .createQueryBuilder()
            .relation(User, 'roles')
            .of(user)
            .addAndRemove(user.roles, actualRelationships);
    
        /**
         * Update only the table USER.
         */
        await getRepository(User)
            .createQueryBuilder()
            .update()
            .set({
                name: user.name,
                username: user.username,
                active: user.active
            })
            .where('id = :id', {id: user.id})
            .execute();
    
        /**
         * Return the updated user
         */
        return await getUser(user.id, true, true)
    };
    
        2
  •  6
  •   Jonathan    7 年前

    因此,以下内容对我起到了作用:

      subjectIds.forEach(async id => {
      await connection
        .createQueryBuilder()
        .relation(Note, 'subjects')
        .of(note)
        .add(id);
    });
    

    不过,我还是觉得回购协议。save()方法 应该 工作

        3
  •  4
  •   JudgeFudge    7 年前

    默认情况下,级联设置为false,可以按如下方式启用:

    @Entity()
    export class Note {
    @PrimaryGeneratedColumn('uuid')
    id: string;
    
    @ManyToMany(() => Subject, (subject: Subject) => subject.notes, { cascade: true })
    subjects: Subject[];
    
    推荐文章