postgresql - 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;
解决方案
推荐阅读
- java - 解压缩使用 java.util.zip.Inflater 编码的 gzip base64
- python - 由于二进制文件的签名无效且二进制文件未签名,因此无法公证 .pkg 文件
- uber-api - 如何从 Uber SDK android 和 iOS 获取请求的乘车详情?
- node.js - “anymatch”的完整性检查失败(计算的完整性与我们的记录不匹配,得到
- android-jetpack-compose - 如何在 Jetpack Compose 中预览 LazyPagingItems/Paging 3 库
- python - Python API json 文件到 Jupyter 中的 Pandas 数据框
- python - SQLAlchemy 的多对多插入如何工作?
- flutter - 在颤振项目中的 pubspec.yaml 中应用获取依赖项时出现退出代码 1 错误
- android - 如何为 Jetpack Compose 中的列表实现“对齐中心”功能?
- python - flask run app.py 给出 OSError: [WinError 10013] 试图以访问权限禁止的方式访问套接字