如何使用Typeorm仅返回关系的某些列

Ale*_*ira 2 postgresql typescript typeorm

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

这是我的代码:

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

这是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"
   }
}
Run Code Online (Sandbox Code Playgroud)

这是我想要的输出:

{
"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",

   }
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*0rn 18

如果您更愿意使用存储库 API 而不是 queryBuilder,则可以这样做

return await this.repository.findOne({
  where: { id },
  select: {
    userId: {
      id: true,
      name: true
    },
    offerId: {
      id: true,
      offerDrescription: true
    }
  },
  relations: {
    userId: true,
    offerId: true,
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 14

尝试这样的事情:

...findOne({
    select: {
        id: true,
        createdAt: true,
        userId: {
          id: true,
          name: true,
        },
        offerId: {
          id: true,
          offerDrescription: true,
        },
      },
      ...
      where: {...},
})
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不适用于多对一关系?(例如“选择:{提供:{id:true}}”) (2认同)

iY1*_*1NQ 8

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

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

Run Code Online (Sandbox Code Playgroud)