我在使用光滑构成链式插入查询时遇到问题。我想插入一行,返回主键,然后将一个带有外键的新行插入我刚刚插入的行。
我尝试使用flatmap将第一个插入的结果链接到第二个插入中,但是下面的代码似乎只执行第一个插入到"用户"表,而不是第二次插入"列表"
示例代码如下,请提前感谢您的帮助!
package com.example.jdbc
import slick.driver.PostgresDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
object DatabaseControllerMin {
lazy val db = Database.forConfig("postgres")
lazy val recreateTables = DBIO.seq(
// drop the old tables
(users.schema ++ lists.schema).drop,
// Create the tables, including primary and foreign keys
(users.schema ++ lists.schema).create
)
class Users(tag: Tag) extends Table[(Int, String)](tag, "users") {
def id = column[Int]("user_id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = (id, name)
}
lazy val users = TableQuery[Users]
class Lists(tag: Tag) extends Table[(Int, String, Int)](tag, "lists") {
def id = column[Int]("list_id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def userId = column[Int]("user_id")
def * = (id, name, userId)
def user = foreignKey("users", userId, users)(_.id)
}
lazy val lists = TableQuery[Lists]
def recreateDatabase = {
try {
val q = recreateTables andThen {
users returning users.map(_.id) into ((user, id) => user.copy(_1 = id)) +=(0, "Tyler")
} flatMap {
user => {
lists +=(0, s"${user._2}'s List", user._1)
}
}
db.run(q)
} finally db.close
}
def main(args: Array[String]) {
recreateDatabase onComplete {
case Success(x) => {
println("Success!!!")
}
case Failure(t) => {
println("Failure")
t.printStackTrace
}
}
}
}