问题
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