typeorm basic join explanation

DDave picture DDave · Nov 4, 2018 · Viewed 15.6k times · Source

accord to guide typeorm: https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#inner-and-left-joins

I don't understand very well this part:

(type => Photo, photo => photo.user)

what does mean type? what does mean photo => photo. ? . it's not good explained on the link.

Partial code:

Import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from "typeorm";
import {Photo} from "./Photo";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany(type => Photo, photo => photo.user)
    photos: Photo[];
}

and on the code:

const user = await createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne();

from where comes ""user.photos"?

Answer

Splitty picture Splitty · Nov 9, 2018

First question: (type => Photo, photo => photo.user)

The decorator for @OneToManytakes two functions, first one returns the related Entity, the second, returns the related entity's "foreign key" property. Since "type" isn't even used you actually don't need it. I omit type completely using @OneToMany(()=> Photo, photo => photo.user) Hasn't been an issue for me.

Second question: where comes "user.photos"

The leftJoinAndSelect("user.photos", "photo") references the property photos defined in the User entity. It's the last line in the User class.