Comparing type mapped values in Slick queries

久未见 提交于 2019-12-05 12:17:59
cmbaxter

When in doubt with Slick, go check out the unit tests. After reading their docs on mapping in a custom type and then looking at their unit tests, I got your query code to compile by changing it to:

def queryByFavoriteType(ftype : FavoriteType)(implicit s: Session) = {
  for(f <- Favorites if f.favoriteType === (ftype:FavoriteType)) yield f
}

Also, I had imported the H2Driver just to get things to compile (import scala.slick.driver.H2Driver.simple._). I was assuming that you also had imported whatever driver it is that you need for your db.

EDIT

My full code example is as follows:

import scala.slick.driver.PostgresDriver.simple._
import scala.slick.session.Session

sealed case class FavoriteType(mapping: String) {
  override def toString = mapping.capitalize
}

case class Favorite(ft:FavoriteType, foo:String)
object FavoriteType {
  object Exam extends FavoriteType("examen")
  object Topic extends FavoriteType("onderwerp")
  object Paper extends FavoriteType("profielwerkstuk")

  val values = Seq(Exam , Topic , Paper )
}

object Favorites extends Table[Favorite]("favorites") {
  // Convert the favoriteTypes to strings for the database
  implicit val favoriteMapping = MappedTypeMapper.base[FavoriteType, String](
    {favType => FavoriteType.values.find(_ == favType).get.mapping},
    {mapping => FavoriteType.values.find(_.mapping == mapping).get}
  )

  def favoriteType = column[FavoriteType]("type")
  def foo = column[String]("foo")

  def * = favoriteType ~ foo <> (Favorite.apply _, Favorite.unapply _)

  def queryByFavoriteType(ftype : FavoriteType)(implicit s: Session) = {
    for(f <- Favorites if f.favoriteType === (ftype:FavoriteType)) yield f
  }   
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!