• 创建多对多关系

    创建多对多关系

    假设一个 photo 可以放在多个 albums 中,每个 albums 可以包含多个 photo。让我们创建一个Album类:

    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需要指定这是关系的所有者方。

    现在添加反向关系到Photo类:

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

    运行后,ORM 将创建album_photos_photo_albums_联结表。

    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. +-------------+--------------+----------------------------+

    记得在 ORM 中使用 ConnectionOptions 注册Album类:

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

    现在让我们将 albums 和 photos 插入我们的数据库:

    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.getRepository(Photo).findOne(1, { relations: ["albums"] });

    loadedPhoto 如下所示:

    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. }