• 创建多对一/一对多关系

    创建多对一/一对多关系

    让我们创建一个多对一/一对多的关系。假设一个 photo 有一个 author,每个 author 都可以有多个 photos。首先让我们创建一个Author类:

    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 包含反向关系。OneToMany 总是反向的, 并且总是与 ManyToOne一起出现。

    现在让我们将关系的所有者方添加到 Photo 实体中:

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

    在多对一/一对多的关系中,拥有方总是多对一的。这意味着使用@ManyToOne的类将存储相关对象的 id。运行应用程序后,ORM 将创建author表:

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

    它还将修改photo表,添加新的author列并为其创建外键:

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