gpt4 book ai didi

postgresql - 如何仅返回与 Typeorm 的关系的某些列

转载 作者:行者123 更新时间:2023-12-04 14:45:35 25 4
gpt4 key购买 nike

好的,我在获取与 typeorm 的关系时遇到了麻烦,当我运行该服务时,它会从关系中返回所有数据,而我只需要特定字段,例如 id 和 name。

这是我的代码:

async findById(id: string): Promise<UsersUseOfferHistoric> {
return await this.repository.findOne({
where: { id },
relations: ['userId', 'offerId'],
});
}

这是json输出:
{
"id": "da0fd04e-17c6-4412-b342-a4361d191468",
"createdAt": "2020-01-07T19:48:30.840Z",
"userId": {
"id": "bdc00227-569f-44b5-9bdd-c8de03661ebd",
"name": "Alexandre Vieira",
"cpf": "10443771430",
"email": "av.souza2018@gmail.com",
"password": "asjdsifjdsfasf",
"imagePath": "/me.png",
"active": true,
"lastLogin": "2020-01-07T19:40:26.850Z",
"createdAt": "2020-01-07T19:40:26.850Z",
"updatedAt": "2020-01-07T19:40:26.850Z"
},
"offerId": {
"id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779",
"offerDrescription": "Nova oferta top",
"discountCoupon": " Desconto top",
"discountValidity": "2020-01-07T14:18:19.803Z",
"discountPercentage": 20,
"discountQuantityLimit": 50,
"createdAt": "2020-01-07T19:45:33.589Z",
"updatedAt": "2020-01-07T19:45:33.589Z"
}
}

这是我想要的输出:
{
"id": "da0fd04e-17c6-4412-b342-a4361d191468",
"createdAt": "2020-01-07T19:48:30.840Z",
"userId": {
"id": "bdc00227-569f-44b5-9bdd-c8de03661ebd",
"name": "Alexandre Vieira",

},
"offerId": {
"id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779",
"offerDrescription": "Nova oferta top",

}
}

最佳答案

findOne函数接受 select: ['id', 'createdAt']属性,您可以在其中过滤传出关系的字段。要显式选择连接表的返回字段(使用 relations 属性隐式地进行左连接),您必须使用 query builder .

await getRepository(Foo).createQueryBuilder('foo')
.where({ id: 1})
.select(['foo.id', 'foo.createdAt', 'bar.id', 'bar.name'])
.leftJoin('foo.bars', 'bar') // bar is the joined table
.getMany();

关于postgresql - 如何仅返回与 Typeorm 的关系的某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59645009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com