pat*_*rit 4 orm code-generation scala slick slick-2.0
我使用光滑的2.x的codegen功能从数据库模式生成Scala模型.但是,是否可以遍历外键约束以生成相关模型,例如,如果我有此模式
CREATE TABLE people(id INT PRIMARY KEY AUTO INCREMENT, name VARCHAR(31));
CREATE TABLE dogs(name VARCHAR(31), ownerId INT FOREIGN KEY people(id));
Run Code Online (Sandbox Code Playgroud)
我从光滑中得到以下模型:
case class PeopleRow(id: Int, name: String)
case class DogsRow(name: String, ownerId: Int)
Run Code Online (Sandbox Code Playgroud)
但是,我真正想要的是:
case class PeopleRow(id: Int, name: String)
case class DogsRow(name: String, owner: PeopleRow)
Run Code Online (Sandbox Code Playgroud)
甚至更好:
case class PeopleRow(id: Int, name: String) {
  def dogs: List[DogsRow]   // return items from dogs table that has this.id as ownerId
}
case class DogsRow(name: String, ownerId: People) {
  lazy val owner: People  // lazy on-demand or, can be a def too
}
Run Code Online (Sandbox Code Playgroud)
无论如何都要覆盖光滑的codegen来做到这一点?
不要这样做.Slick的核心优势之一来自撰写查询.虽然你想要的是你可能正在打破这种力量.而是写查询!
implicit class PersonExtension(q: Query[Person,PersonRow]){
  def dogs = q.join(Dog).on(_.id === _.ownerId).map(_._2)
}
implicit class DogExtension(q: Query[Person,PersonRow]){
  def owner = q.join(Person).on(_.ownerId === _.id).map(_._2)
}
val personQuery = Person.filter(_.id === someId)
val person = personQuery.first
val dogsQuery = personQuery.dogs
val dogs = dogsQuery.run
val ownerQuery = dogsQuery.owner
val owner = ownerQuery.first
Run Code Online (Sandbox Code Playgroud)
因此,请使用旧查询基于您的新狗查询.优点是您不会以这种方式对一个查询进行硬编码,但您可以进一步构建.只想要棕色的狗?没问题:
val brownDogsQuery = personQuery.dogs.filter(_.color === "brown")
Run Code Online (Sandbox Code Playgroud)
您当然可以使用代码生成器自动生成这些隐式类.
有关的影片:
http://slick.typesafe.com/docs/