我想插入一个包含外键的新记录。 例如,将新记录插入到条形图中,并且新记录具有由表格foos的查询结果找到的id。
这是一个代码示例:
import scala.slick.driver.H2Driver.simple._
object Test {
case class FooRecord(id:Int, str: String)
class Foos(tag: Tag) extends Table[FooRecord](tag, "users") {
def id = column[Int]("ID", O.PrimaryKey)
def str = column[String]("EMAIL", O.NotNull)
def * = (id, str) <> (FooRecord.tupled, FooRecord.unapply _)
}
val foos = TableQuery[Foos]
case class BarRecord(app_id:Int, name: String)
class Bars(tag: Tag) extends Table[BarRecord](tag, "apps") {
def foo_id = column[Int]("FOO_ID")
def str = column[String]("STR", O.NotNull)
def * = (foo_id, str) <> (BarRecord.tupled, BarRecord.unapply _)
def foo_fk = foreignKey("FOO_FK", foo_id, foos)(_.id)
}
val bars = TableQuery[Bars]
def main(args: Array[String]): Unit = {
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
implicit session =>
foos.filter(_.str === "ABC").map { f =>
// Insert a new record that contains foo's id as a foreign key to bars.
// bars.insert(BarRecord(f.id, "DEF"))
// [error] found : scala.slick.lifted.Column[Int]
// [error] required: Int
bars.insert(BarRecord(1, "DEF")) // OK
}
}
}
}
我遇到了编译错误。外键的类型是Column [Int],但BarRecord id类型是Int。 有没有什么好方法可以获得Int值?或者是否有更优雅的方式可以插入来自另一个表的查询结果的值?
答案 0 :(得分:1)
您的查询返回提升的查询,而不是Int
值:
val fooIdColumn: lifted.Query[lifted.Column[Int], Int] =
foos.filter(_.str === "ABC").map(f => f.id)
您可以使用run
并取回Seq[Int]
(因为可能会有多个结果):
val fooIds: Seq[Int] =
foos.filter(_.str === "ABC").map(x => x.id).run
或firstOption
和getOrElse
取回Int
:
val fooId: Int =
foos.filter(_.str === "ABC").map(x => x.id).firstOption.getOrElse(0)