TypeORM add custom column without losing object tree

房东的猫 提交于 2019-12-08 14:15:44

问题


following the docs if i want to add a custom column to the select eg. "sum(a.id) as count" i have to add ".getRaw...()", if i have a join (table A one to may table B) i'm losing the object tree ([{id: 1, bs: [...]}]) and the result is the raw sql list of repeated A rows ([{id: 1, b_id: 1}, {id: 1, b_id: 2}])

This is how i do it in sequelize

    const user = await User.findOne({
      attributes: ['id', [Sequelize.fn('COUNT', Sequelize.col('id')), 'no_hats']],
      include: [
        {
          model: UserKey,
          as: 'keys',
          attributes: ['id']
        }
      ],
      where: {
        email: 'xxx'
      },
      group: ['id']
    });

and the result is what i expected

{
 id: 'be14f8a0-b3c7-11e9-91c7-47a1f55db49b',
 no_hats: 1,
 keys: [ [UserKey], [UserKey] ] 
}

When i do it with typeorm

    const user = await userRepo
      .createQueryBuilder('u')
      .select('u.id')
      .addSelect('COUNT(u.id)', 'no_hats')
      .addSelect('keys.id')
      .where('u.email = :email', { email: 'xxx' })
      .leftJoin('u.userKeys', 'keys')
      .groupBy('u.id')
      .addGroupBy('keys.id')
      .getRawMany();

and the result:

[
  {
        u_id: 'be14f8a0-b3c7-11e9-91c7-47a1f55db49b',
        keys_id: '29996d0f-beb4-48e9-bd5b-596bc255de0c',
        no_hats: '1' 
  },
  {
        u_id: 'be14f8a0-b3c7-11e9-91c7-47a1f55db49b',
        keys_id: '47b03fe8-20fc-4322-99a0-3ecb5223b00f',
        no_hats: '1' 
  }
]

thanks in advance

来源:https://stackoverflow.com/questions/58087849/typeorm-add-custom-column-without-losing-object-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!