Search code examples
nestjstypeorm

How to get distinct values from typeorm find "query"


I'm trying to implement the following query on typeorm but unable to filter out the distinct values.

SELECT DISTINCT name, description, style, spec2, div FROM clothes WHERE name = 'CMD' and div  in ('B01', 'B06', 'B07', 'B09')

My existing code is like following.

    this._itemRepository.find({
      where: {
        "name" : "values",
        "div" : In(["v1","v2"])
      },
   })

find() method's parameter is FindManyOptions type but it doesn't have any attribute related to distinct values. Please help me to find a way


Solution

  • There is no such option for the find method. For more advanced queries you can use the queryBuilder like so:

    this._itemRepository.createQueryBuilder('clothes')
    .select(['name', 'description', 'style', 'spec2', 'div'])
    .where('name = CMD AND div IN (B01, B06, B07, B09)')
    .distinct()
    

    EDIT: (Maybe you need to put the strings like "CMD", "B01", ... into quotes)

    Or you can do sth like that too:

    this._itemRepository.createQueryBuilder('clothes')
    .select('DISTINCT(name)')
    .where('name = CMD AND div IN (B01, B06, B07, B09)')