首页 > 解决方案 > TypeORM NestJS - 将实体数组保存到相关表中无法正常工作

问题描述

我有一个与另一个实体有一对多关系的实体。

  @OneToMany(() => Asset, (asset: Asset) => asset.collection, { eager:true, cascade: true})
  assets: Asset[];

  @ManyToOne(()=> Collection, (collection: Collection) => collection.assets)
  collection: Collection;

现在,当我想创建一个资产数组并将其与新创建的集合一起保存时,它仅在我对所有对象进行循环并使用 new Asset() 时才有效,但在我使用 repository.create( ) 方法并在保存之前将结果传递给 collection.assets。

这有效

const assets = [];

      for(let i=0; i< assetResponse.length; i++){
        let asset = new Asset();
        asset.id = assetResponse[i].id;
        asset.token_id = "232323";
        assets.push(asset);
      }

      const stats = await getCustomRepository(CollectionStatsRepository).create(
        statsResponse.stats as Object,
      );

      collection.assets = assets;
      collection.stats = stats;

      return await getCustomRepository(CollectionRepository).save(collection);

当我使用以下尝试时,它会如何将所有内容存储在表中,但不存储任何关系。在资产表中,collectionId 始终为空,当我找到所有集合项时,它没有显示任何资产 []

   const collection = await getCustomRepository(CollectionRepository).create(
        collectionResponse.collection as Object,
      );

      const assets = await  getRepository(Asset).create(
        await this.fetchAssets(collection)  //fetchAssets returns an array of object matching the Asset Schema
      );

     
      const stats = await getCustomRepository(CollectionStatsRepository).create(
        statsResponse.stats as Object,
      );

      collection.assets = assets;
      collection.stats = stats; 

标签: postgresqlnestjstypeorm

解决方案


推荐阅读