Search code examples
scalaplayframeworkslick

How to filter TableQuery with the list of IDs?


I'm really new to Slick and Scala and I'm strugling with filtering the query with the list of ids.

productsNeededIds // = "1,2,3,4,5" - list of Ids of products

Question: How can I use .filter to get a query with all the ids from the splitted list?

   def productsWithIds(productsNeededIds: String)(implicit ec: ExecutionContext): Future[List[ProductsREST]] = {

    var splitedArray :Array[String] = productsNeededIds.split(",")
    val query = Products.filter(_.prodId === splitedArray)// what should be here instead of ===splitedArray?
}

Solution

  • You should use the inSet method:

    def productsWithIds(productsNeededIds: String)(implicit ec: ExecutionContext): Future[List[ProductsREST]] = {
    
      val splitedSet: Set[String] = productsNeededIds.split(",").toSet
      val query = Products.filter(_.prodId.inSet(splitedSet))
    }
    

    That's assuming your product IDs are strings. If they're Ints instead, you should map your splittedSet to Ints first, of course.