• 保存一对一的关系

    保存一对一的关系

    现在来创建一个 photo,它的元信息将它们互相连接起来。

    1. import { createConnection } from "typeorm";
    2. import { Photo } from "./entity/Photo";
    3. import { PhotoMetadata } from "./entity/PhotoMetadata";
    4. createConnection(/*...*/)
    5. .then(async connection => {
    6. // 创建 photo
    7. let photo = new Photo();
    8. photo.name = "Me and Bears";
    9. photo.description = "I am near polar bears";
    10. photo.filename = "photo-with-bears.jpg";
    11. photo.isPublished = true;
    12. // 创建 photo metadata
    13. let metadata = new PhotoMetadata();
    14. metadata.height = 640;
    15. metadata.width = 480;
    16. metadata.compressed = true;
    17. metadata.comment = "cybershoot";
    18. metadata.orientation = "portait";
    19. metadata.photo = photo; // 联接两者
    20. // 获取实体 repositories
    21. let photoRepository = connection.getRepository(Photo);
    22. let metadataRepository = connection.getRepository(PhotoMetadata);
    23. // 先保存photo
    24. await photoRepository.save(photo);
    25. // 然后保存photo的metadata
    26. await metadataRepository.save(metadata);
    27. // 完成
    28. console.log("Metadata is saved, and relation between metadata and photo is created in the database too");
    29. })
    30. .catch(error => console.log(error));