Chuyển đến nội dung

Bài 17 · Relations

Many-to-Many Relations

Model many-to-many relations with TypeORM @ManyToMany and @JoinTable and Sequelize belongsToMany, add extra columns with an explicit join entity, and see junction tables in a runnable demo.

A student takes many courses; a course has many students. Posts have many tags and tags label many posts. A many-to-many relation cannot be stored with a single foreign key; it needs a third table, the junction table (also called join or pivot table), with one row per link.

Library code is read-only; the stand-ins run the junction-table SQL on SQLite.

erDiagram
  STUDENT ||--o{ ENROLLMENT : has
  COURSE ||--o{ ENROLLMENT : has
  ENROLLMENT {
    int student_id PK
    int course_id PK
    string grade
  }

The junction table holds two foreign keys, usually as a composite primary key.

TypeORM: @ManyToMany and @JoinTable

TypeScript
@Entity()
export class Student {
  @PrimaryGeneratedColumn() id!: number;
  @Column() name!: string;

  @ManyToMany(() => Course, (course) => course.students)
  @JoinTable({ name: "enrollments" })        // owning side creates the junction table
  courses!: Course[];
}

@Entity()
export class Course {
  @PrimaryGeneratedColumn() id!: number;
  @Column() title!: string;

  @ManyToMany(() => Student, (student) => student.courses)
  students!: Student[];
}

@JoinTable() goes on one side only. TypeORM names the junction table and its columns (studentId, courseId) unless you pass options.

TypeScript
const algebra = await courses.save({ title: "Algebra" });
const ana = await students.save({ name: "Ana", courses: [algebra] });  // inserts the link row

const loaded = await students.findOne({ where: { id: ana.id }, relations: { courses: true } });

// Add and remove links without loading everything:
await AppDataSource.createQueryBuilder().relation(Student, "courses").of(ana).add(2);
await AppDataSource.createQueryBuilder().relation(Student, "courses").of(ana).remove(1);

Sequelize: belongsToMany

TypeScript
Student.belongsToMany(Course, { through: "enrollments", as: "courses", foreignKey: "studentId", otherKey: "courseId" });
Course.belongsToMany(Student, { through: "enrollments", as: "students", foreignKey: "courseId", otherKey: "studentId" });

through names the junction table (or passes a model). Both sides declare the relation. You get helper methods:

TypeScript
await ana.addCourse(algebra);               // INSERT into enrollments
await ana.addCourses([algebra, physics]);
await ana.removeCourse(algebra);
await ana.setCourses([physics]);             // replace the whole set
const list = await ana.getCourses();
const withCourses = await Student.findAll({ include: [{ model: Course, as: "courses" }] });

Extra columns: use an explicit join entity

The moment the link itself has data (a grade, an enrolment date, a role), the plain many-to-many is not enough. Promote the junction table to a real entity and use two one-to-many relations.

TypeScript
// TypeORM
@Entity()
export class Enrollment {
  @PrimaryColumn() studentId!: number;
  @PrimaryColumn() courseId!: number;
  @Column({ type: "varchar", nullable: true }) grade!: string | null;
  @CreateDateColumn() enrolledAt!: Date;

  @ManyToOne(() => Student, (s) => s.enrollments, { onDelete: "CASCADE" })
  @JoinColumn({ name: "studentId" })
  student!: Student;

  @ManyToOne(() => Course, (c) => c.enrollments, { onDelete: "CASCADE" })
  @JoinColumn({ name: "courseId" })
  course!: Course;
}
TypeScript
// Sequelize: pass a model to through
const Enrollment = sequelize.define("Enrollment", { grade: DataTypes.STRING });
Student.belongsToMany(Course, { through: Enrollment });
Course.belongsToMany(Student, { through: Enrollment });
await ana.addCourse(algebra, { through: { grade: "A" } });

Sequelize lets a belongsToMany carry extra attributes directly. TypeORM does not, so the explicit entity is the way there.

The SQL that runs

Node.js Junction table and joins

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Helper methods, stand-in version

Sequelize's add, remove and set come down to inserting and deleting junction rows. Note that set computes the difference.

Node.js add, remove, set

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Pitfalls

  • Forgetting @JoinTable (TypeORM): no junction table is created and the relation silently has no storage.
  • Putting @JoinTable on both sides: pick one.
  • Duplicate links: use a composite primary key (or a unique pair) so the database rejects them.
  • Cascades on many-to-many: deleting a student should delete only the junction rows, never the courses. onDelete: "CASCADE" on the junction foreign keys does exactly that.
  • Loading both directions at once can multiply rows; load what you display.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does a many-to-many relation need a third table?

    The junction table stores one row per link, with a key to each side.
  2. 2. Where do you put @JoinTable in TypeORM?

    One side declares @JoinTable and owns the junction table.
  3. 3. What does Sequelize student.setCourses([2, 3]) do?

    set adds the missing links and removes the extra ones.
  4. 4. The link needs a grade column. What should you do in TypeORM?

    Data on the link itself belongs in a join entity.

Summary

  • Many-to-many uses a junction table with two foreign keys, usually a composite primary key.
  • TypeORM: @ManyToMany on both sides and @JoinTable on one; Sequelize: belongsToMany with through.
  • Sequelize adds addX, removeX, setX and getX helpers; TypeORM uses save with arrays or the relation() builder.
  • When the link carries data, model it as its own entity.
  • Constrain duplicates and cascade deletes on the junction table only.

Next: Loading Strategies and Cascades

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.