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
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' }]
}
                        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