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"?
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.
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)
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.
First question: (type => Photo, photo => photo.user)
The decorator for @OneToMany
takes 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With