I am trying to create two entities - Assignment
and Lesson
. Each Lesson
can have multiple Assignment
s and each Assignment
can be part of one Lesson
. When I create a Lesson
with Assignment
s in it, the Assignemnt
s get created, they are added to the assignments
array and everything works.
When I create a Lesson
and then try to add a new Assignment
to it, the Assignment
is created, it is linked to the correct Lesson
but the assignments
field in the Lesson is not updated.
Is this how it is supposed to work or is there any way to update the assignments
array in Lesson
?
Below is my code. I am using a sqlite in-memory database
Assignment.ts
import { Entity, Column, PrimaryGeneratedColumn, TableInheritance, ManyToOne, JoinColumn } from 'typeorm';
import { Lesson } from './Lesson';
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export abstract class Assignment {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToOne(() => Lesson, (lesson) => lesson.assignments, { eager: true })
@Column('json')
lesson: Lesson;
}
Lesson.ts
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { Assignment } from './Assignment';
@Entity()
export class Lesson {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Assignment, (assignment) => assignment.lesson, { cascade: true })
@Column('json')
assignments: Assignment[];
}
I have tried adding @JoinColumn()
to the @ManyToOne
relation but nothing changed
The solution was to remove the @Column
annotation from both of the fields - assignments and lesson.
I could also add a filed lessonId: number
with the @Column
annotation to store the lesson id in the Assignment.