rysv
rysv

Reputation: 3420

Scala Slick filter after mapping query value

Is there a way to transform an id (from external hash to database primary key id) before doing Slick query by ID. For other slick queries I can override case class apply / unapply to map between external and internal IDs. However, when querying by ID using filter() I am not aware of any way of doing without mapping before calling filter.

val res = items.filter(i => i.id === itemId)

Here the itemId is externally visible ID and not the id value stored in the database. Wonder if TableQuery can be extended and change the id value before calling filter.

Hope the question makes sense.

Upvotes: 0

Views: 1178

Answers (1)

C4stor
C4stor

Reputation: 8026

You can do something like this :

type ItemId = String

  implicit def ItemIdToRepInt(itemId: ItemId): Rep[Int] = {
    itemId.toInt*2 // We let the implicit conversion provided by slick from Int to Rep[Int] occur here
  }

  val itemId: ItemId = "1"

  db.run(MyTable.filter(i => i.id === itemId).result) //will filter on id = 2

Hope that makes sense for you :-)

Also, if ItemId is actually Int, you need to more accurately convert from Item to Rep[Int] otherwise you'll get in an infinite loop of implicit conversions.

Upvotes: 1

Related Questions