gpt4 book ai didi

scala - 光滑,如何将查询映射到继承表模型?

转载 作者:行者123 更新时间:2023-12-04 03:52:40 26 4
gpt4 key购买 nike

光滑,如何将查询映射到继承表模型?
IE,

我有表A,B,C
A是“父”表,B&C是“子”表
我想知道的是我该如何使用平滑模型,以便A将成为抽象的B&C具体类型,而查询A中的一行将导致B或C对象

类似于JPA的InheritanceType.TABLE_PER_CLASS

最佳答案

我们需要做几件事。首先找到一种将层次结构映射到表的方法。在这种情况下,我使用的是存储类型的列。但是您也可以使用其他技巧。

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"))
})
}
}

现在确定特定的子类型,您可以执行以下操作:
Query(new MyTable).foreach { 
case ChildOne(a, b, c) => //childone
case ChildTwo(a, b, d) => childtwo
}

关于scala - 光滑,如何将查询映射到继承表模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com