repositoryfilteringqueryingtypeorm

Typeorm: Check if a property is either value 1, 2, 3 or n


I want to get all tasks that have a certain role. I have an array of strings for which I want to get the tasks.

Query:

return this.createQueryBuilder('task')
    .select(this.baseSelect)
    .where('task.role = :role', { role }) // What here?
    .getMany();

This code of course only gets the tasks for which the role is that one value. How can I check multiple values?


Solution

  • For searching in multiple roles you can use the IN operator:

    OLD VERSION of TypeORM

    return this.createQueryBuilder('task')
        .select(this.baseSelect)
        .where('task.role IN(:roles)', {roles: [role1, role2, role3]});
        .getMany();
    

    NEW VERSION of TypeORM

    As mentioned by user Christophe Geers, In the new version, you will have to use the spread syntax.

    return this.createQueryBuilder('task')
        .select(this.baseSelect)
        .where('task.role IN(:...roles)', {roles: [role1, role2, role3]});
        .getMany();