【问题标题】:Set Many-to-Many relationship decorator for two entities vs create a third entity?为两个实体设置多对多关系装饰器与创建第三个实体?
【发布时间】:2022-01-23 13:25:32
【问题描述】:

在 TypeORM 中,假设我使用 MySQL 数据库并且有两个实体:Student 和 Course。

一个学生可以学习多门课程,一个课程可以被多个学生注册。

所以解决n-n关系有两种方法:

  • 方法#1official documents 建议我将@ManyToMany@JoinTable 装饰器添加到其中之一。但是,我发现在使用大型后端时很难维护代码。
// src/entity/Student.ts
@Entity()
export class Student {
  //...
}
// src/entity/Course.ts
@Entity()
export class Course {
  //...
  @ManyToMany(() => Student)
  @JoinTable()
  students: Student[];
}
  • 方法#2:创建一个实体(如StudentCourse)将它们联系起来。 TypeORM 要求我在中间表中添加一个主键。将主键添加到架构中的所有中间表中会浪费时间,并且会增加大小容量。
// src/entity/Student.ts
@Entity()
export class Student {
  //...
  @OneToMany(type => StudentCourse, studentCourse => studentCourse.student)
  studentCourses!: StudentCourse[];
}
// src/entity/Course.ts
@Entity()
export class Course {
  //...
  @OneToMany(type => StudentCourse, studentCourse => studentCourse.course)
  studentCourses!: StudentCourse[];
}
// src/entity/StudentCourse.ts
@Entity()
export class StudentCourse {
  @PrimaryGeneratedColumn({ type: "int", name: "id" })
  id!: number;

  // Some custom columns...

  @ManyToOne(type => Student, student => student.studentCourses)
  @JoinColumn([{ name: "student_id", referencedColumnName: "id" }])
  student: Student;

  @ManyToOne(type => Course, course => course.studentCourses)
  @JoinColumn([{ name: "course_id", referencedColumnName: "id" }])
  course: Course;
}

我想知道的是:我应该使用哪种方法来处理多对多关系?什么时候,为什么?它们之间的优缺点是什么?

【问题讨论】:

    标签: mysql node.js typescript typeorm


    【解决方案1】:

    对于第一种方法@ManyToMany
    当我们在想要建立的关系之间没有任何其他属性时,我们会使用它
    你的情况这种方法适合你

    Ps:@ManyToMany 为我们创建关联表

    2/ 我们使用第二种方法是当我们需要添加更多信息时,例如如果需要添加一个教室,日期然后创建一个新实体是必须的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2021-12-21
      • 1970-01-01
      • 2016-01-13
      • 2018-07-22
      相关资源
      最近更新 更多