【问题标题】:How to insert an entity with OneToMany relation in NestJS?如何在 NestJS 中插入具有 OneToMany 关系的实体?
【发布时间】:2019-07-24 17:04:11
【问题描述】:

在 typeorm 官方文档https://typeorm.io/#/many-to-one-one-to-many-relations 中有如何做到这一点的描述。但是我不能在 NestJS 中使用 Repositoryinsert 方法做同样的事情。

我已经写了这些实体(其他列被省略了)

@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

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    检查级联属性

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

    如果你做类似的事情

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

    如果你打电话给this.repository.save(news),它会保存新闻和图片。还有更新。在 typeorm 文档上查看更多关于此的文档。

    【讨论】:

    • 您将如何处理删除不在 images[] 数组中的实体,例如对于用户从数组中删除一张图像的更新,它仍然存在于数据库中,但不会删除该项目typeorm/nestjs 尝试将图片上的 newsId 设置为 null @andressh11
    • 这里有一个 github 问题:github.com/typeorm/typeorm/issues/1460
    【解决方案2】:

    声明new News() 会创建一个新实体,但不会将其保存到数据库中。您首先需要insert.save() news 对象,然后将其添加到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
      // ...
    }
    

    【讨论】:

    • 谢谢,我试过这种方式,但.insert 返回InsertResult 对象,而不是news 实体。我从insertResults 中检索到id 并将id 设置为news,使用该消息创建了图像实体,并且可以正常工作!
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多