如何在Typeorm querybuilder中选择特定的列

时间:2020-10-17 09:59:22

标签: sql typescript typeorm

我试图通过连接typeorm中的表来选择特定的列。

当我看到以下材料时,有示例代码。

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;
}

例如,我想要的结果如下。where user.name =="Timber"

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

有什么好的方法可以做到这一点吗?

谢谢

2 个答案:

答案 0 :(得分:2)

当你想选择特定的列时,你必须像下面这样使用 getRawOne,

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

答案 1 :(得分:1)

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();

通过此查询,您将获得:

{
  id: 1,
  name: 'Timber',
  photos: [{ url: 'someurl1' }, ..., { url: 'someurlN' }]
}