Creating a many-to-many relation

Let’s create a many-to-one / many-to-many relation.Let’s say a photo can be in many albums, and each album can contain many photos.Let’s create an Album class:

  1. import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from "typeorm";
  2. @Entity()
  3. export class Album {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. name: string;
  8. @ManyToMany(type => Photo, photo => photo.albums)
  9. @JoinTable()
  10. photos: Photo[];
  11. }

@JoinTable is required to specify that this is the owner side of the relationship.

Now let’s add the inverse side of our relation to the Photo class:

  1. export class Photo {
  2. /// ... other columns
  3. @ManyToMany(type => Album, album => album.photos)
  4. albums: Album[];
  5. }

After you run the application, the ORM will create a album_photos_photo_albums junction table:

  1. +-------------+--------------+----------------------------+
  2. | album_photos_photo_albums |
  3. +-------------+--------------+----------------------------+
  4. | album_id | int(11) | PRIMARY KEY FOREIGN KEY |
  5. | photo_id | int(11) | PRIMARY KEY FOREIGN KEY |
  6. +-------------+--------------+----------------------------+

Don’t forget to register the Album class with your connection in the ORM:

  1. const options: ConnectionOptions = {
  2. // ... other options
  3. entities: [Photo, PhotoMetadata, Author, Album]
  4. };

Now let’s insert albums and photos to our database:

  1. let connection = await createConnection(options);
  2. // create a few albums
  3. let album1 = new Album();
  4. album1.name = "Bears";
  5. await connection.manager.save(album1);
  6. let album2 = new Album();
  7. album2.name = "Me";
  8. await connection.manager.save(album2);
  9. // create a few photos
  10. let photo = new Photo();
  11. photo.name = "Me and Bears";
  12. photo.description = "I am near polar bears";
  13. photo.filename = "photo-with-bears.jpg";
  14. photo.albums = [album1, album2];
  15. await connection.manager.save(photo);
  16. // now our photo is saved and albums are attached to it
  17. // now lets load them:
  18. const loadedPhoto = await connection
  19. .getRepository(Photo)
  20. .findOne(1, { relations: ["albums"] });

loadedPhoto will be equal to:

  1. {
  2. id: 1,
  3. name: "Me and Bears",
  4. description: "I am near polar bears",
  5. filename: "photo-with-bears.jpg",
  6. albums: [{
  7. id: 1,
  8. name: "Bears"
  9. }, {
  10. id: 2,
  11. name: "Me"
  12. }]
  13. }