【问题标题】:How can I add item to many-to-many relationed table with TypeORM如何使用 TypeORM 将项目添加到多对多关联表
【发布时间】:2022-02-21 22:03:43
【问题描述】:

我需要有关 typeorm、typegraphql 的多对多问题的帮助。我尝试了很多方法将项目添加到 M-T-M 关系表中,但无法做到。我遵循了 TypeORM 文档,但我认为我遗漏了一些东西。

当我尝试从学院获取教师时,它返回未定义。应该是什么类型的?我认为它是一个数组,我可以轻松地将一个项目推送到它,或者传播旧值并添加一个项目。但是,上述方法都不起作用。

 @ObjectType()
@Entity()
export class Faculty extends BaseEntity {
  @Field(() => ID)
  @PrimaryColumn()
  id: string;

  @Field(() => [Department])
  @OneToMany(() => Department, (department) => department.faculty)
  departments: Department[];

  @Field(() => [Teacher], { nullable: true })
  @ManyToMany(() => Teacher)
  @JoinTable()
  teachers: Teacher[];

  @BeforeInsert()
  setId() {
    this.id = uuid();
  }
}



@ObjectType()
@Entity()
export class Teacher extends BaseEntity {
  @Field(() => ID)
  @PrimaryColumn()
  id: string;

  @Field(() => [Faculty])
  @ManyToMany(() => Faculty, (faculty) => faculty.teachers)
  faculties: Faculty[];

  @BeforeInsert()
  setId() {
    this.id = uuid();
  }
}



 @Mutation(() => Teacher)
  async addTeacherToFaculty(
    @Arg('teacherId') teacher_id: string,
    @Arg('facultyId') faculty_id: string
  ): Promise<Teacher> {
    const teacher = await Teacher.findOne({ where: { id: teacher_id } });

    let faculty = await Faculty.findOne({ where: { id: faculty_id } });

    if (!teacher) {
      throw new Error('Invalid credentials, please provide correct teacher ID');
    }

    if (!faculty) {
      throw new Error('Invalid credentials, please provide correct faculty ID');
    }

    const { teachers } = faculty;

    if (teachers && teachers.length == 0) {
      faculty.teachers = [teacher];
    } else {
      faculty.teachers?.push(teacher);
    }

    console.log(faculty.teachers);

    await faculty.save();

    return teacher;
  }

【问题讨论】:

    标签: typescript typeorm typegraphql


    【解决方案1】:

    管理多对多关系的最简单方法是创建自己的自定义连接表。因此,Teacher 将与自定义连接表(让我们称之为连接表 TeacherFaculty)具有一对多的关系,并且 Faculty 也将与 TeacherFaculty 具有一对多的关系。 TeacherFaculty 将反过来与 Teacher 和 Faculty 建立多对一的关系。然后,您可以为它们的 id 定义列,这些列将被引用为它们的连接列。例如

    @ObjectType()
    @Entity()
    export class Faculty extends BaseEntity {
      @Field(() => ID)
      @PrimaryColumn()
      id: string;
    
      @Field(() => [Department])
      @OneToMany(() => Department, (department) => department.faculty)
      departments: Department[];
    
      @OneToMany(() => TeacherFaculty, (tf) => tf.faculty)
      teacherConn: Promise<TeacherFaculty[]>;
    
      @BeforeInsert()
      setId() {
        this.id = uuid();
      }
    }
    
    @ObjectType()
    @Entity()
    export class Teacher extends BaseEntity {
      @Field(() => ID)
      @PrimaryColumn()
      id: string;
    
      @OneToMany(() => TeacherFaculty, (tf) => tf.teacher)
      facultyConn: Promise<TeacherFaculty[]>;
    
      @BeforeInsert()
      setId() {
        this.id = uuid();
      }
    }
    
    
    @Entity()
    export class TeacherFaculty extends BaseEntity {
      @PrimaryColumn()
      teacherId: number;
    
      @PrimaryColumn()
      facultyId: number;
    
      @ManyToOne(() => Teacher, (teacher) => teacher.facultyConn, {
        primary: true,
      })
      @JoinColumn({ name: "teacherId" })
      teacher: Promise<Teacher>;
    
      @ManyToOne(() => Faculty, (faculty) => faculty.teacherConn, {
        primary: true,
      })
      @JoinColumn({ name: "facultyId" })
      faculty: Promise<Faculty>;
    }
    

    现在添加项目变得如此简单:

    @Mutation(() => Teacher)
      async addTeacherToFaculty(
        @Arg('teacherId') teacher_id: string,
        @Arg('facultyId') faculty_id: string
      ): Promise<Teacher> {
        try {
         await TeacherFaculty.create({ teacherId:teacher_id , facultyId: faculty_id}).save();
        } catch (err) {
          console.log(err)          
        }
    const teacher = await Teacher.findOne({where:{id:teacher_id}, relations:["facultyConn"]})
    return teacher
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多