4

我正在使用slick 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));

我从 slick 获得以下模型:

case class PeopleRow(id: Int, name: String)
case class DogsRow(name: String, ownerId: Int)

但是,我真正想要的是:

case class PeopleRow(id: Int, name: String)
case class DogsRow(name: String, owner: PeopleRow)

甚至更好:

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
}

反正有没有覆盖光滑的代码生成来做到这一点?

4

1 回答 1

5

不要这样做。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

因此,请使用旧查询作为新狗查询的基础。优点是您不会以这种方式对一个查询进行硬编码,但您可以进一步编写。只想要棕色的狗吗?没问题:

val brownDogsQuery = personQuery.dogs.filter(_.color === "brown")

您当然可以使用代码生成器自动生成这些隐式类。

有关的影片:

  • 斯卡拉交流 2013
  • Scala 用户组柏林演讲,2013 年 12 月
  • 2014 年 Scala 日演讲

http://slick.typesafe.com/docs/

于 2014-07-19T07:24:05.367 回答