Reputation: 5299
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
Upvotes: 25
Views: 66626
Reputation: 87
When you want to select particular columns you have to use getRawOne like below,
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.select(['user.id', 'user.name', 'photo.url'])
.where("user.name = :name", { name: "Timber" })
.getRawOne();
Upvotes: 9
Reputation: 3356
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' }]
}
Upvotes: 34