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

前端 未结 2 1666
有刺的猬
有刺的猬 2020-12-30 10:49

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

I have table A, B, C A is the \"parent\" table and B & C are \"child\" tables What I would like to

相关标签:
2条回答
  • 2020-12-30 11:07

    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

    0 讨论(0)
  • 2020-12-30 11:22

    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
    }
    
    0 讨论(0)
提交回复
热议问题