Chanlito
Chanlito

Reputation: 2472

TypeORM selected subquery result not showing after querying

So I have the following query:

const [discussions, total] = await em
    .createQueryBuilder(Discussion, 'd')
    .select(['d', 'u.id', 'u.firstName', 'u.lastName', 'u.image'])
    .addSelect(
      qb =>
        qb
          .select('COUNT(*)', 'commentCount')
          .from(Comment, 'c')
          .where('c.discussion_id = d.id'),
      'commentCount',
    )
    .leftJoin('d.user', 'u', 'd.user_id = u.id')
    .where('d.project_id = :projectId', { projectId })
    .orderBy({ 'd.updated_date': 'DESC' })
    .limit(limit)
    .offset(offset)
    .getManyAndCount();

And I'm adding a subquery select as you can see.

The query executed successfully, but the discussions array doesn't have property commentCount returned.

What am I missing?

Upvotes: 1

Views: 6641

Answers (1)

Pavan Bahuguni
Pavan Bahuguni

Reputation: 2025

Use getRaw or getRawMany instead of getManyAndCount. When you are selecting fields, typeorm can't map it to the Entities which you have defined, because there might be aliases in the select. So you have to get that data as raw data.

Upvotes: 9

Related Questions