我有两个模型(例如,Supplier和Coffee),并且 Coffee 模型具有对 Supplier 模型的外键引用。在 ddl 期间,我希望这种关系存在于表创建中。但我也希望能够通过 Coffee 对象引用 Supplier 对象,例如coffeeObj.supplier.name
. 下面是我的虚拟代码。我正在使用MappedTable、foreignKey和TypeMapper。
import scala.slick.driver.H2Driver.simple._
import Database.threadLocalSession
object SlickTest {
// Supplier
case class Supplier(id: Option[Int], name: String)
object Suppliers extends Table[Supplier]("supplier") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = id.? ~ name <> (Supplier, Supplier.unapply _)
def findOneById(id: Int): Supplier =
this.map { e => e }.where(r => r.id === id).firstOption.get
}
// Implicit Conversion from Supplier to Int
implicit val supTypeMapper = MappedTypeMapper.base[Supplier, Int](
{ s => s.id.get }, { id => Suppliers.findOneById(id) })
// Coffee
case class Coffee(name: Option[String], sup: Supplier, price: Double)
object Coffees extends Table[Coffee]("coffee") {
def name = column[String]("cof_name", O.PrimaryKey)
def sup = column[Supplier]("supplier")
def price = column[Double]("price")
def * = name.? ~ sup ~ price <> (Coffee, Coffee.unapply _)
def supplier = foreignKey("SUP_FK", sup, Suppliers)(_.id)
}
}
代码在定义的最后一行失败supplier
。有人能解释一下吗?