Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an entity with OneToMany relation in NestJS?

Tags:

typeorm

nestjs

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.

like image 233
epsilon Avatar asked Mar 03 '19 03:03

epsilon


People also ask

What typeorm relations are used in nestjs?

1 Generally, TypeORM relations used in NestJS are simple and dev-friendly. The code which you've written defines parameters which are already predefined. For example, @PrimaryColumn({ type: "varchar", name: "id", unique: true })

Does nest integrate with typeorm?

For convenience, Nest provides tight integration with TypeORM and Sequelize out-of-the-box with the @nestjs/typeormand @nestjs/sequelizepackages respectively, which we'll cover in the current chapter, and Mongoose with @nestjs/mongoose, which is covered in this chapter.

How do I create a one-to-many relationship with bookentity?

type => BookEntity is a function that returns the class of the entity with which we want to make our relationship. book => book.user states which column is to be used by ‘BookEntity’ to get the associated user. Now, we have set a One-to-Many relationship from the ‘UserEntity’ side.

What is the use of @OneToMany annotation in JPA?

For convenience, to take advantage of the entity state transitions and the dirty checking mechanism, many developers choose to map the child entities as a collection in the parent object, and, for this purpose, JPA offers the @OneToMany annotation.


2 Answers

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.

like image 161
andressh11 Avatar answered Oct 18 '22 10:10

andressh11


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
  // ...
}
like image 34
Jacob Avatar answered Oct 18 '22 10:10

Jacob