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.
You need many-to-many relation. Take a look on TypeOrm implementation here