Creating a many-to-one / one-to-many relation

Let’s create a many-to-one / one-to-many relation.Let’s say a photo has one author, and each author can have many photos.First, let’s create an Author class:

  1. import {Entity, Column, PrimaryGeneratedColumn, OneToMany, JoinColumn} from "typeorm";
  2. import {Photo} from "./Photo";
  3. @Entity()
  4. export class Author {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @OneToMany(type => Photo, photo => photo.author) // note: we will create author property in the Photo class below
  10. photos: Photo[];
  11. }

Author contains an inverse side of a relation.OneToMany is always an inverse side of relation, and it can’t exist without ManyToOne on the other side of the relation.

Now let’s add the owner side of the relation into the Photo entity:

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

In many-to-one / one-to-many relation, the owner side is always many-to-one.It means that the class that uses @ManyToOne will store the id of the related object.

After you run the application, the ORM will create the author table:

  1. +-------------+--------------+----------------------------+
  2. | author |
  3. +-------------+--------------+----------------------------+
  4. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  5. | name | varchar(255) | |
  6. +-------------+--------------+----------------------------+

It will also modify the photo table, adding a new author column and creating a foreign key for it:

  1. +-------------+--------------+----------------------------+
  2. | photo |
  3. +-------------+--------------+----------------------------+
  4. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  5. | name | varchar(255) | |
  6. | description | varchar(255) | |
  7. | filename | varchar(255) | |
  8. | isPublished | boolean | |
  9. | authorId | int(11) | FOREIGN KEY |
  10. +-------------+--------------+----------------------------+