Search code examples
typeorm

How to find all entities with a certain value in its array element?


My entity contains an array element with enum type.
I have to find all entities with a certain enum value contained in its array element.

Like this.

enum AccessoryType {
  Patio = 'PATIO',
  DriveWay = 'DRIVE_WAY',
  ...
}

enum MaterialType {
  Granite = 'GRANITE',
  BlueStone = 'BLUE_STONE',
  NaturalStone = 'NATURAL_STONE',
  ...
}

@Injectable()
class IdeaEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  url: string;

  @Column({ type: 'enum', enum: AccessoryType })
  accessoryType: AccessoryType;

  @ApiProperty({ enum: MaterialType, isArray: true })
  @Column({
    type: 'enum',
    enum: MaterialType,
    array: true,
  })
  materialTypes: MaterialType[];
}

function myQueryFunction(accessoryType: AccessoryType, materialTypes: MaterialType[], skip: number, take: number): Promise<IdeaEntity[]> {
  ...

  return ideaRepository.find({
    where: {
      accessoryType: accessoryType,
      materialTypes: {
        contains: materialTypes
      }
    }, skip, take
  });
  ...
}

Or at least (with single value provided):

where: {
  ...
  materialTypes: {
    contains: MaterialType.Granite
  }
  ...
}

Is there a way to use typeorm function to achieve this?


Solution

  • Have your tried this way: https://github.com/typeorm/typeorm/issues/1401

    But I recommend you to create another MaterialTypesEntity with relations in each tables (with this approach there is no problem to find entities)