How to filter and count relation items in typeorm? How to filter and count relation items in typeorm? database database

How to filter and count relation items in typeorm?


Try:

const found = await this.usersRepository.createQueryBuilder('user')   .loadRelationCountAndMap('user.unreadEventCount', 'user.events', 'event', (qb) => qb.where('event.readAt IS NULL'))   .getMany();

About loadRelationCountAndMap:

1st argument is the property name the count would be mapped to - that would be a field on your entity that is NOT a @Column.

2nd is the relation name

3rd is the alias to use with the query

4th is the optional QueryBuilder to filter further, in your case it's checking if the readAt column is null