How to select only single/multiple fields from joined entity in Typeorm
12,634
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.select(['user', 'photo.url', 'photo.alt'])
.where("user.name = :name", { name: "Timber" })
.getOne();
or
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.addSelect(['photo.url', 'photo.alt'])
.where("user.name = :name", { name: "Timber" })
.getOne();
(not sure about the second one)
Author by
Dev AKS
Updated on June 07, 2022Comments
-
Dev AKS almost 2 years
accord to TypeOrm doc: https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#joining-relations
We can query the joined entity's field that will populate all its field into the response. I am not sure how to restrict only to few selected fields(single/multiple), I tried adding 'select([])' but it is not working in the generated SQL query I can see it is querying all the fields.
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[]; } import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm"; import {User} from "./User"; @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @Column() url: string; @Column() alt: string; @ManyToOne(type => User, user => user.photos) user: User; }
and on the code:
const user = await createQueryBuilder("user") .leftJoinAndSelect("user.photos", "photo") .where("user.name = :name", { name: "Timber" }) .getOne();
The above code gives the output as -
{ id: 1, name: "Timber", photos: [{ id: 1, url: "me-with-chakram.jpg", alt: "Me With Chakram" }, { id: 2, url: "me-with-trees.jpg", alt: "Me With Trees" }] }
Is there a way I can query only 'url' and 'alt' so the output will look something like this -
{ id: 1, name: "Timber", photos: [{ url: "me-with-chakram.jpg", alt: "Me With Chakram" }, { url: "me-with-trees.jpg", alt: "Me With Trees" }] }
-
Dev AKS over 3 yearsThanks for your answer. I figured eventually but you were quick with your response :)
-
Dev AKS over 3 yearsThe first one is correct, the second is idle for function use (SUM, AVG, etc).
-
Samuel Goldenbaum about 3 yearsThis returns ALL photo fields
-
D.Zotov over 2 yearsHow your answer is different from the accepted one?
-
Jhon Zambrano over 2 yearsMy answer is just a complement, and refers to the fact you can not remove at all the
user
entity (who owns relationship) fromselect
statement regardless you don't need any field fromuser
justphoto
, you must select at least one field fromuser
entity -
Dipak over 2 yearsIs the output of query same as requested question?