我正在使用slick 2.x's 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));
我从光滑中获得以下模型:
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
}
无论如何都要覆盖光滑的codegen来执行此操作吗?
答案 0 :(得分:5)
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")
您当然可以使用代码生成器自动生成这些隐式类。
相关视频: