14

There is the description how to do this in typeorm official docs https://typeorm.io/#/many-to-one-one-to-many-relations. But I can't do the same in NestJS with Repository and insert method.

I have written these entities (other columns were omitted)

    @Entity()
    export class News {
      @OneToMany(type => NewsImage, image => image.news)
      public images: NewsImage[];
    }
    
    @Entity()
    export class NewsImage {
      @ManyToOne(type => News, news => news.images)
      public news: News;
    }

I have tried something like this

    function first() {
      const news = new News();
      const image = new NewsImage();
      news.images = [ image ];
      return from(this.newsRepo.insert(news))
        .pipe(
          switchMap(() => this.imageRepo.insert(image)),
        );
    }
    
    function second() {
      const news = new News();
      const image = new NewsImage();
      image.news = news;
      return from(this.imageRepo.insert(image))
        .pipe(
          switchMap(() => this.newsRepo.insert(news)),
        )
    }

It inserts news and image, but image's newsId is null.

2 Answers 2

35

Check cascade property

@Entity()
export class News {
  @OneToMany(type => NewsImage, image => image.news, { cascade: ['insert', 'update'] })
  public images: NewsImage[];
}

Then if you do something like

    let news = {
        images: [{
            date: "",
            etc: ""
        }],
        title: ""
    }

If then you call this.repository.save(news) it will save the news and the images. And updates too. Check more docs about this on typeorm docs.

Sign up to request clarification or add additional context in comments.

2 Comments

How would you handle removing entities that are not in the images[] array, say for an update where an user removes one image from the array, it still exists in the database but instead of deleting the item typeorm/nestjs tries to set the newsId to null on the image @andressh11
here is a github issue regarding this : github.com/typeorm/typeorm/issues/1460 .
1

Declaring new News() creates a new entity but does not save it to the database. You first need to insert or .save() the news object and then add it to image.

async function first() {
  // you can .save() it however you want, the point is it must be saved to the db
  const news = await News.create({ title: 'Async rules the world' }).save()
  const image = new NewsImage()
  image.news = news // now news has an id from the database
  // ...
}

1 Comment

Thanks, I tried this way, but .insert returns InsertResult object, not news entity. I retrieved id from insertResults and set id to news, created image entity with that news and it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.