Inverse side of the relationship

Relations can be unidirectional or bidirectional.Currently, our relation between PhotoMetadata and Photo is unidirectional.The owner of the relation is PhotoMetadata, and Photo doesn’t know anything about PhotoMetadata.This makes it complicated to access PhotoMetadata from the Photo side.To fix this issue we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional.Let’s modify our entities:

  1. import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from "typeorm";
  2. import {Photo} from "./Photo";
  3. @Entity()
  4. export class PhotoMetadata {
  5. /* ... other columns */
  6. @OneToOne(type => Photo, photo => photo.metadata)
  7. @JoinColumn()
  8. photo: Photo;
  9. }
  1. import {Entity, Column, PrimaryGeneratedColumn, OneToOne} from "typeorm";
  2. import {PhotoMetadata} from "./PhotoMetadata";
  3. @Entity()
  4. export class Photo {
  5. /* ... other columns */
  6. @OneToOne(type => PhotoMetadata, photoMetadata => photoMetadata.photo)
  7. metadata: PhotoMetadata;
  8. }

photo => photo.metadata is a function that returns the name of the inverse side of the relation.Here we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class.Instead of passing a function that returns a property of the photo, you could alternatively simply pass a string to @OneToOne decorator, like "metadata".But we used this function-typed approach to make our refactoring easier.

Note that we should use @JoinColumn decorator only on one side of a relation.Whichever side you put this decorator on will be the owning side of the relationship.The owning side of a relationship contains a column with a foreign key in the database.