Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a many-to-many relationship with TypeORM

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!

like image 684
Jonathan Avatar asked Jan 10 '19 21:01

Jonathan


2 Answers

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[];
like image 147
JudgeFudge Avatar answered Oct 02 '22 17:10

JudgeFudge


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

like image 24
Jonathan Avatar answered Oct 02 '22 19:10

Jonathan