Issue
In TypeORM, suppose I use MySQL database and there are two entities: Student and Course.
A student can learn many course, and a course can be enrolled by many student.
So there are two ways to solve n-n relationship:
- Method #1: the official documents suggests me to add
@ManyToMany
and@JoinTable
decorators into one of them. However, I find it hard to maintain the code when working with a large-scaled backend.
// src/entity/Student.ts
@Entity()
export class Student {
//...
}
// src/entity/Course.ts
@Entity()
export class Course {
//...
@ManyToMany(() => Student)
@JoinTable()
students: Student[];
}
- Method #2: Create an entity (like StudentCourse) that link between them. TypeORM requires me to add a primary key into the middle table. This additional step will be time-wasting to add a primary key into all middle tables in a schema and this will increase size capacity.
// 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;
}
What I want to know is: Which method should I use to deal with Many-to-Many relationship? When and why? What are the pros and cons between them?
Solution
For the first method @ManyToMany
:
We use it when we don't have any other properties we weed between that relationship we want to build,
in your case this method suits you
Ps: @ManyToMany create an association table for us
2/ We use the second method is when we need to add more information for example if need to add a classroom, date then creating a new entity is a must.
Answered By - Youba
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.