Creating a one-to-one relation

Let’s create a one-to-one relation with another class.Let’s create a new class in PhotoMetadata.ts. This PhotoMetadata class is supposed to contain our photo’s additional meta-information:

  1. import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from "typeorm";
  2. import {Photo} from "./Photo";
  3. @Entity()
  4. export class PhotoMetadata {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column("int")
  8. height: number;
  9. @Column("int")
  10. width: number;
  11. @Column()
  12. orientation: string;
  13. @Column()
  14. compressed: boolean;
  15. @Column()
  16. comment: string;
  17. @OneToOne(type => Photo)
  18. @JoinColumn()
  19. photo: Photo;
  20. }

Here, we are using a new decorator called @OneToOne. It allows us to create a one-to-one relationship between two entities.type => Photo is a function that returns the class of the entity with which we want to make our relationship.We are forced to use a function that returns a class, instead of using the class directly, because of the language specifics.We can also write it as () => Photo, but we use type => Photo as a convention to increase code readability.The type variable itself does not contain anything.

We also add a @JoinColumn decorator, which indicates that this side of the relationship will own the relationship.Relations can be unidirectional or bidirectional.Only one side of relational can be owning.Using @JoinColumn decorator is required on the owner side of the relationship.

If you run the app, you’ll see a newly generated table, and it will contain a column with a foreign key for the photo relation:

  1. +-------------+--------------+----------------------------+
  2. | photo_metadata |
  3. +-------------+--------------+----------------------------+
  4. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  5. | height | int(11) | |
  6. | width | int(11) | |
  7. | comment | varchar(255) | |
  8. | compressed | boolean | |
  9. | orientation | varchar(255) | |
  10. | photoId | int(11) | FOREIGN KEY |
  11. +-------------+--------------+----------------------------+