- 保存一对一的关系
保存一对一的关系
现在来创建一个 photo,它的元信息将它们互相连接起来。
import { createConnection } from "typeorm";import { Photo } from "./entity/Photo";import { PhotoMetadata } from "./entity/PhotoMetadata";createConnection(/*...*/).then(async connection => {// 创建 photolet 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 metadatalet metadata = new PhotoMetadata();metadata.height = 640;metadata.width = 480;metadata.compressed = true;metadata.comment = "cybershoot";metadata.orientation = "portait";metadata.photo = photo; // 联接两者// 获取实体 repositorieslet photoRepository = connection.getRepository(Photo);let metadataRepository = connection.getRepository(PhotoMetadata);// 先保存photoawait photoRepository.save(photo);// 然后保存photo的metadataawait metadataRepository.save(metadata);// 完成console.log("Metadata is saved, and relation between metadata and photo is created in the database too");}).catch(error => console.log(error));
