Using cascades to automatically save related objects
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:
export class Photo {
/// ... other columns
@OneToOne(type => PhotoMetadata, metadata => metadata.photo, {
cascade: true,
})
metadata: PhotoMetadata;
}
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.
createConnection(options).then(async connection => {
// create photo object
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;
// create photo metadata object
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
// get repository
let photoRepository = connection.getRepository(Photo);
// saving a photo also save the metadata
await photoRepository.save(photo);
console.log("Photo is saved, photo metadata is saved too.")
}).catch(error => console.log(error));