为两个实体设置多对多关系装饰器还是创建第三个实体?

Set Many-to-Many relationship decorator for two entities vs create a third entity?

在 TypeORM 中,假设我使用 MySQL 数据库并且有两个实体:学生和课程。

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

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

// src/entity/Student.ts
@Entity()
export class Student {
  //...
}
// src/entity/Course.ts
@Entity()
export class Course {
  //...
  @ManyToMany(() => Student)
  @JoinTable()
  students: Student[];
}
// 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;
}

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

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

Ps: @ManyToMany 为我们创建一个关联table

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