We can setup cascade options in our relations, in the cases when we want our related object to be saved whenever the other object is saved.Let’s change our photo’s @OneToOne decorator a bit:

  1. export class Photo {
  2. /// ... other columns
  3. @OneToOne(type => PhotoMetadata, metadata => metadata.photo, {
  4. cascade: true,
  5. })
  6. metadata: PhotoMetadata;
  7. }

Using cascade allows us not to separately save photo and separately save metadata objects now.Now we can simply save a photo object, and the metadata object will be saved automatically because of cascade options.

  1. createConnection(options).then(async connection => {
  2. // create photo object
  3. let photo = new Photo();
  4. photo.name = "Me and Bears";
  5. photo.description = "I am near polar bears";
  6. photo.filename = "photo-with-bears.jpg";
  7. photo.isPublished = true;
  8. // create photo metadata object
  9. let metadata = new PhotoMetadata();
  10. metadata.height = 640;
  11. metadata.width = 480;
  12. metadata.compressed = true;
  13. metadata.comment = "cybershoot";
  14. metadata.orientation = "portait";
  15. photo.metadata = metadata; // this way we connect them
  16. // get repository
  17. let photoRepository = connection.getRepository(Photo);
  18. // saving a photo also save the metadata
  19. await photoRepository.save(photo);
  20. console.log("Photo is saved, photo metadata is saved too.")
  21. }).catch(error => console.log(error));