Search code examples
nestjstypeorm

TypeOrm query builder


I can't figure out how to write the following MySql statement using TypeOrm Query Builder

SELECT reg.id FROM farm.reg WHERE grpId = 'ABC';

this select is returning just the id's but my query builder is returning the entire objects.

In this moment I have this function in my NestJs service but I need to use 'map' and I don't want to..

 async getGrupIds(entity: string, grpId: string) {

        console.log(entity, grpId);
        const ids = await getRepository(reg)
        .createQueryBuilder(entity)
        .where('reg.grpId = :grpId', {grpId: grpId})
        .getMany();
        console.log(ids);
        return ids.map(o => o.id);

    }

Thank you


Solution

  • Try to use getRawMany() instead of getMany() if you want to select some specified fields of your entity:

    //I suppose you have a *grpId* variable in your function 
    
    const ids = await getRepository(Reg)
        .createQueryBuilder('reg')
        .select('reg.grpId', 'id')
        .where('reg.grpId = :grpId', { grpId } )
        .getRawMany();
        console.log(ids);
        return ids    
    }
    

    https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#getting-values-using-querybuilder