Slick, how to map a query to an inheritance table model?

混江龙づ霸主 提交于 2019-11-30 07:08:38

We need to do couple of things. First find a way to map the hierarchy to an table. In this case I am using a column that stores the type. But you can use some other tricks as well.

trait Base {
  val a: Int
  val b: String
}

case class ChildOne(val a: Int, val b: String, val c: String) extends Base
case class ChildTwo(val a: Int, val b: String, val d: Int) extends Base

class MyTable extends Table[Base]("SOME_TABLE") {
  def a = column[Int]("a")
  def b = column[String]("b")
  def c = column[String]("c", O.Nullable)
  def d = column[Int]("d", O.Nullable)
  def e = column[String]("model_type")

  //mapping based on model type column
  def * = a ~ b ~ c.? ~ d.? ~ e <> ({ t => t match {
    case (a, b, Some(c), _, "ChildOne") => ChildOne(a, b, c)
    case (a, b, _, Some(d), "ChildTwo") => ChildTwo(a, b, d)
  }}, {
    case ChildOne(a, b, c) => Some((a, b, Some(c), None, "ChildOne"))
    case ChildTwo(a, b, d) => Some((a, b, None, Some(d), "ChildTwo"))
  })
}
} 

Now to determine specific sub type you can do following:

Query(new MyTable).foreach { 
     case ChildOne(a, b, c) => //childone
     case ChildTwo(a, b, d) => childtwo
}

Slick does not support this directly. Some databases can help you with inheritance though, so you should be able to get something close to the desired effect.

Have a look at the inheritance documentation in PostgreSQL

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!