I am having issues updating a entity that has a many-to-many reln, curious if I am doing something wrong, or more specifically what is the right way to do this
Consider the following entities ...
@Entity
class Subject
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@ManyToMany(() => Note, note => note.subjects)
@JoinTable()
notes: Note[];
...
@Entity()
export class Note {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToMany(() => Subject, (subject: Subject) => subject.notes)
subjects: Subject[];
In my code I find the node and then try to update it and save like so ...
const note = await noteRepo.findOneOrFail(noteId);
const foundSubjects = await subjectRepo.findByIds(Array.from(subjectIds));
note.subjects = foundSubjects;
noteRepo.save(note);
But alas, the subjects are not saved on the note.
What is the right way to do this?
Thanks!
By default cascading is set to false, you can enable this as follows:
@Entity()
export class Note {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToMany(() => Subject, (subject: Subject) => subject.notes, { cascade: true })
subjects: Subject[];
So the following got it working for me:
subjectIds.forEach(async id => {
await connection
.createQueryBuilder()
.relation(Note, 'subjects')
.of(note)
.add(id);
});
Though, I still kind of feel that the repo.save() method should work
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