简体   繁体   中英

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.

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.

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