Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 223
DDave Avatar asked Nov 04 '18 14:11

DDave


People also ask

How do you join in TypeORM?

TypeORM has a method called innerJoinAndSelect . You use plain innerJoin . That is why user table is not selected from. Once you change that part to innerJoinAndSelect , watch table will be selected from.

What is Createquerybuilder?

QueryBuilder is one of the most powerful features of TypeORM - it allows you to build SQL queries using elegant and convenient syntax, execute them and get automatically transformed entities. Simple example of QueryBuilder : const firstUser = await dataSource. . getRepository(User)

How do I use QueryBuilder TypeORM?

Learn TypeORM for NestJS Fast Query builder is used build complex SQL queries in an easy way. It is initialized from Connection method and QueryRunner objects. We can create QueryBuilder in three ways.


1 Answers

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.

like image 54
Splitty Avatar answered Sep 23 '22 07:09

Splitty