I am trying to create a table called "classes" that acts as a link between two tables, "user" and "class_group". I want to create three primary keys in "classes" that are also foreign keys. Two of the keys should come from the "id" column of the "user" table and be named "student_id" and "teacher_id". The third key should come from the "id" column of the "class_group" table and be named "class_id".
To set this up, I created "Many-to-one" relationships in the "classes" entity and "One-to-many" relationships in the "user" and "class_group" entity. However, I ended up with six columns in the "classes" table instead of three, and I suspect that I made a mistake in my implementation.
Can someone help me figure out what went wrong?

@Entity()
export class Classes {
@PrimaryColumn()
classId: number;
@PrimaryColumn()
studentId: number;
@PrimaryColumn()
teacherId: number;
@ManyToOne(() => User, user => user.classes)
@JoinColumn({ name: 'student_id' })
student: User;
@ManyToOne(() => User, user => user.classes)
@JoinColumn({ name: 'teacher_id' })
teacher: User;
@ManyToOne(() => ClassGroup, classGroup => classGroup.classes)
@JoinColumn({ name: 'class_id' })
classGroup: ClassGroup;
}
@Entity()
export class User {
...
@OneToMany(() => Classes, classes => classes.student)
classes: Classes[];
@OneToMany(() => Classes, classes => classes.teacher)
classesAsTeacher: Classes[];
}
@Entity()
export class ClassGroup {
...
@OneToMany(() => Classes, classes => classes.classGroup)
classes: Classes[];
}
I just copied your classes definitions as below:
@Entity()
export class Classes {
@PrimaryColumn()
classId: number;
@PrimaryColumn()
studentId: number;
@PrimaryColumn()
teacherId: number;
@ManyToOne(() => User, user => user.classes)
@JoinColumn({ name: 'student_id' })
student: User;
@ManyToOne(() => User, user => user.classes)
@JoinColumn({ name: 'teacher_id' })
teacher: User;
@ManyToOne(() => ClassGroup, classGroup => classGroup.classes)
@JoinColumn({ name: 'class_id' })
classGroup: ClassGroup;
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@OneToMany(() => Classes, (classes) => classes.student)
classes: Classes[];
@OneToMany(() => Classes, (classes) => classes.teacher)
classesAsTeacher: Classes[];
}
@Entity()
export class ClassGroup {
@PrimaryGeneratedColumn()
id: number;
@OneToMany(() => Classes, (classes) => classes.classGroup)
classes: Classes[];
}
And this code generates all table as you want, see image below:

So maybe is the TypeOrm version, please check the code to see if there is any difference.
Hope it helps. Rgds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With