如何在 NestJS 中插入具有 OneToMany 关系的实体? [英] How to insert an entity with OneToMany relation in NestJS?

查看:84
本文介绍了如何在 NestJS 中插入具有 OneToMany 关系的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typeorm 官方文档中描述了如何执行此操作 https://typeorm.io/#/many-to-one-one-to-many-relations.但是我不能用 Repositoryinsert 方法在 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;
}

我试过这样的事情

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)),
    )
}

插入新闻和图片,但图片的newsIdnull.

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

推荐答案

检查级联属性

@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: ""
    }

如果你调用 this.repository.save(news) 它将保存新闻和图像.还有更新.在 typeorm 文档上查看更多关于此的文档.

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.

这篇关于如何在 NestJS 中插入具有 OneToMany 关系的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆