Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific columns in typeorm querybuilder

I tried to select specific columns by joining tables in typeorm.

When I see following materials there is sample code.

https://orkhan.gitbook.io/typeorm/docs/select-query-builder#joining-relations

const user = await createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne();
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[];
}
import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm";
import {User} from "./User";

@Entity()
export class Photo {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    url: string;

    @ManyToOne(type => User, user => user.photos)
    user: User;
}

for example my desired result is following.where user.name =="Timber"

{
id: user.id
name: user.name
url: photo.url
}

Are there any good way to achieve this ?

Thanks

like image 798
Heisenberg Avatar asked Oct 17 '20 09:10

Heisenberg


1 Answers

const user = await createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .select(['user.id', 'user.name', 'photo.url']) // added selection
    .where("user.name = :name", { name: "Timber" })
    .getOne();

By this query, you'll get:

{
  id: 1,
  name: 'Timber',
  photos: [{ url: 'someurl1' }, ..., { url: 'someurlN' }]
}
like image 158
Art Olshansky Avatar answered Nov 14 '22 21:11

Art Olshansky