【发布时间】:2022-01-23 13:25:32
【问题描述】:
在 TypeORM 中,假设我使用 MySQL 数据库并且有两个实体:Student 和 Course。
一个学生可以学习多门课程,一个课程可以被多个学生注册。
所以解决n-n关系有两种方法:
-
方法#1:official 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