简体   繁体   中英

Filter an array passed from query params. NestJS, TypeORM

I'm using NestJS with TypeORM, database is MySQL, and I'd like to filter multiple parameters that can be passed in.

The frontend has a list of products and filters are applied as query params sent to NestJS, filtering works for a single param eg api.example.com?manufacturer=Acer but how would I filter an Array eg api.example.com?manufacturer=Acer,Toshiba,Asus.

I tried quite a few things in TypeORM, currently using the QueryBuilder to build the array with an if statement if the filter exists if so I'm doing something like a where statement.

.andWhere(manufacturer = filterOne, {filterOne: *manufacturers from the query param*})

But yeah just can't hack something together, tried a couple of things, above is a rough example, did try methods that TypeORM had as an example on filtering arrays but it seemed like it was more for an array of integers only? Regardless, I'm open to any methods that allow for the end result of filtering the example I provided, cheers and thanks again!

You have to use IN to get all data where manufacturer equal the data came from the query, first, you have to convert the query to an array:

var manufacturerParam = filterOne.split(",");

then add it to your query:

.andWhere(manufacturer IN (:filter)", { filter: manufacturerParam  }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM