Search code examples
typeormtypeorm-datamapper

TypeORM basic join explanation


According to typeorm guide

I don't understand this part very well:

(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"?


Solution

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