Kha*_*lah 7 scala type-conversion foreign-key-relationship slick
我有两个模型(比如供应商和咖啡),咖啡模型有供应商模型的外键参考.在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)
}
}
Run Code Online (Sandbox Code Playgroud)
代码在定义的最后一行失败supplier.任何人都可以放光吗?
在Slick中,您不会映射到引用其他案例类的案例类.要解析外键,请使用查询,您可以将其放入可重用性的方法中.
另请参阅我的帖子:https://groups.google.com/d/msg/scalaquery/esFb2DjoHVE/NtMj7BmpE94J
编辑: 您不能在coffeeObj中关注参考,这是一件好事.因为这需要配置像ORM一样的加载策略,这会更复杂,并且会使代码的执行行为变得不那么明显.
延迟加载可能会加载控制器中的coffeeObj和视图中的供应商,这看起来很奇怪,对吧?你可以这样做:
.firstOption.get从您的findOneById方法中删除然后:
val supplierQuery = Query(Suppliers).findById(id)
val coffeeQuery = supplierQuery.join(Coffee).on(...).map(_._2)
// here is what you want, a supplier and the corresponding coffee:
val supplierWithCoffee = (supplierQuery.firstOption,coffeeQuery.f?irstOption)
Run Code Online (Sandbox Code Playgroud)
将连接放入功能中以节省锅炉板.
| 归档时间: |
|
| 查看次数: |
8473 次 |
| 最近记录: |