Typeorm: Easier way to make SELECT COUNT(DISTINCT()) queries

Created on 15 Nov 2017  路  3Comments  路  Source: typeorm/typeorm

I recently switched from Sequelize to TypeORM because I wanted proper typing and decorator support, but I'm struggling with certain queries that were easy to do in Sequelize.

// Sequelize
const count = await logEntry.aggregate('sender_id', 'count', {distinct: true})
console.log(count); // 4 (As a number)
// TypeORM
const count = await logEntry.getRepository().createQueryBuilder('log_entry').select('COUNT(DISTINCT(`sender_id`))', 'count').getRawOne()
console.log(count); // {count: 4} (As an object)

I'm basically writing the SELECT part of the query by hand, is there a better way to do this in TypeORM?

manager and repository query builder discussion help wanted

Most helpful comment

@afurculita
your solution did not work for me. .getCount() always returns the number of rows in the table.

All 3 comments

Not yet. We'll need to make a detailed proposal for this and all similar features and discuss its design first before implementing

@Ionaru this can be done now this way:

const count = await logEntry.getRepository().createQueryBuilder('log_entry').select('DISTINCT(`sender_id`)').getCount();
console.log(count); // 4 (As a number)

@afurculita
your solution did not work for me. .getCount() always returns the number of rows in the table.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pleerock picture pleerock  路  3Comments

niveo picture niveo  路  3Comments

leixu2txtek picture leixu2txtek  路  3Comments

natanielkd picture natanielkd  路  3Comments

cameronpickham picture cameronpickham  路  3Comments