Nestjs how to properly map 2 tables with a middle table

Viewed 1672

I'm using Postgres as database have the next tables:

Students

id: Integer (PK)
name: Text

Subject

id: Integer (PK)
name: Text

student_assignation

student_id: Integer (PK)
subject_id: Integer (PK)

Those tables haven't an Auto-generated PK. So, my entities are:

Student.entity.ts

import { Entity, Column, PrimaryGeneratedColumn, OneToMany, PrimaryColumn } from 'typeorm';
import { student_assignation } from './student_assignation.entity';
import { Subject } from './subject.entity';

@Entity()
export class Student {
  @Column('number')
  @PrimaryColumn()
  id: number;

  @Column('text')
  name: string;

  @OneToMany(type => student_assignation, x => x.subject_id)
  //student_assignations: student_assignation[];
}

Well, here is my question: I'm trying to get all the subjects assigned to a user. In SQL terms, I would define it like:

SELECT 
    u.id, u.name, r.id, r.name
FROM  
    student u INNER JOIN student_assignation ra
        ON u.id = ra.student_id
    INNER JOIN subject r
        ON r.id = ra.subject_id
WHERE
    u.id = 1

But at the moment to convert and use it in nestjs, I have this relation:

@OneToMany(type => student_assignation, x => x.subject_id)

@ManyToOne(type => subject, x => x.id)

But, is not retrieving any information.

2 Answers

You need many-to-many relation. Take a look on TypeOrm implementation here

You have to implement your entities in many-to-many relation:

@Entity()
export class Student {
    @Column('number')
    @PrimaryColumn()
    id: number;

    @Column('text')
    name: string;

    @ManyToMany(type => Subject)
    @JoinTable({ name: 'student_assignation' })
    subjects: Subject[];
}


@Entity()
export class Subject {
    @PrimaryColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(type => Student)
    students: Student[];
}

To retrieve a user with all subjects:

const user = await User.findOne(USER_ID, { relations: ['subjects'] })
console.log(user.subjects);
Related