- 使用 cascades 自动保存相关对象
使用 cascades 自动保存相关对象
我们可以在关系中设置cascade选项,这是就可以在保存其他对象的同时保存相关对象。让我们更改一下的 photo 的@OneToOne装饰器:
export class Photo {/// ... other columns@OneToOne(type => PhotoMetadata, metadata => metadata.photo, {cascade: true})metadata: PhotoMetadata;}
使用cascade允许就不需要边存 photo 边存元数据对象。我们可以简单地保存一个 photo 对象,由于使用了 cascade,metadata 也将自动保存。
createConnection(options).then(async connection => {// 创建 photo 对象let photo = new Photo();photo.name = "Me and Bears";photo.description = "I am near polar bears";photo.filename = "photo-with-bears.jpg";photo.isPublished = true;// 创建 photo metadata 对象let metadata = new PhotoMetadata();metadata.height = 640;metadata.width = 480;metadata.compressed = true;metadata.comment = "cybershoot";metadata.orientation = "portait";photo.metadata = metadata; // this way we connect them// 获取 repositorylet photoRepository = connection.getRepository(Photo);// 保存photo的同时保存metadataawait photoRepository.save(photo);console.log("Photo is saved, photo metadata is saved too.");}).catch(error => console.log(error));
