Many-to-one / one-to-many relations

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

    Here we added @OneToMany to the photos property and specified the target relation type to be Photo.You can omit @JoinColumn in a @ManyToOne / @OneToMany relation.@OneToMany cannot exist without @ManyToOne.If you want to use @OneToMany, @ManyToOne is required. However, the inverse is not required: If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity.Where you set @ManyToOne - its related entity will have “relation id” and foreign key.

    This example will produce following tables:

    1. const photo1 = new Photo();
    2. photo1.url = "me.jpg";
    3. await connection.manager.save(photo1);
    4. const photo2 = new Photo();
    5. photo2.url = "me-and-bears.jpg";
    6. await connection.manager.save(photo2);
    7. const user = new User();
    8. user.name = "John";
    9. user.photos = [photo1, photo2];
    10. await connection.manager.save(user);

    or alternative you can do:

    With cascades enabled you can save this relation with only one save call.

    1. const userRepository = connection.getRepository(User);
    2. const users = await userRepository.find({ relations: ["photos"] });
    3. // or from inverse side
    4. const photoRepository = connection.getRepository(Photo);

    Or using QueryBuilder you can join them:

    With eager loading enabled on a relation you don’t have to specify relation or join it - it will ALWAYS be loaded automatically.