gpt4 book ai didi

scala - Slick:Codegen 外键引用

转载 作者:行者123 更新时间:2023-12-05 01:03:36 27 4
gpt4 key购买 nike

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

我从 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
}

无论如何要覆盖光滑的代码生成器来做到这一点?

最佳答案

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

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

有关的影片:
  • Scala 交换 2013
  • Scala 用户组柏林谈话 2013 年 12 月
  • Scala Days 2014 讲座

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

    关于scala - Slick:Codegen 外键引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24484655/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com