Scala Slick 如何插入具有先前返回的自动增量 ID 的行
Scala Slick How to insert rows with a previously returned autoincremental ID
事情是这样的。
我使用的是 Slick 3.1.0,基本上我有两个模型,一个对另一个有 FK 约束。比方说:
case class FooRecord(id: Option[Int], name: String, oneValue: Int)
class FooTable(tag: Tag) extends Table[FooRecord](tag, "FOO"){
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def name = column[String]("NAME")
def oneValue = column[Int]("ONEVALUE")
}
val fooTable = TableQuery[FooTable]
和
case class BarRecord(id: Option[Int], name: String, foo_id: Int)
class BarTable(tag: Tag) extends Table[BarRecord](tag, "BAR"){
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def name = column[String]("NAME")
def fooId = column[Int]("FOO_ID")
def foo = foreignKey("foo_fk", fooId, fooTable)(_.id)
}
这些是为了存储一个 Foo 和几个 Bars,其中一个 Bar 只有一个 Foo。
我一直在试图弄清楚如何在单个事务上执行完整的插入语句集。即
DBIO.seq(
(fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42),
(barTable returning batTable.map(_id)) += Bar(None, "MyBarname", FOO_KEY)
)
但问题是我找不到将 Foo ID 用作 Bar 实例字段上的 FOO_KEY 的方法。
当然,我可以执行两次 DBAction,但我认为这非常糟糕。
有什么想法吗?
提前致谢
最简单的方法就是对您的 DBIO 事务进行排序并将第一个的结果传递给第二个:
val insertDBIO = for {
fooId <- (fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42)
barId <- (barTable returning batTable.map(_id)) += Bar(None, "MyBarname", fooId)
} yield (fooId, barId)
db.run(insertDBIO.transactionally)
transactionally
调用将确保两者 运行 在同一连接上。
事情是这样的。
我使用的是 Slick 3.1.0,基本上我有两个模型,一个对另一个有 FK 约束。比方说:
case class FooRecord(id: Option[Int], name: String, oneValue: Int)
class FooTable(tag: Tag) extends Table[FooRecord](tag, "FOO"){
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def name = column[String]("NAME")
def oneValue = column[Int]("ONEVALUE")
}
val fooTable = TableQuery[FooTable]
和
case class BarRecord(id: Option[Int], name: String, foo_id: Int)
class BarTable(tag: Tag) extends Table[BarRecord](tag, "BAR"){
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def name = column[String]("NAME")
def fooId = column[Int]("FOO_ID")
def foo = foreignKey("foo_fk", fooId, fooTable)(_.id)
}
这些是为了存储一个 Foo 和几个 Bars,其中一个 Bar 只有一个 Foo。 我一直在试图弄清楚如何在单个事务上执行完整的插入语句集。即
DBIO.seq(
(fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42),
(barTable returning batTable.map(_id)) += Bar(None, "MyBarname", FOO_KEY)
)
但问题是我找不到将 Foo ID 用作 Bar 实例字段上的 FOO_KEY 的方法。 当然,我可以执行两次 DBAction,但我认为这非常糟糕。 有什么想法吗?
提前致谢
最简单的方法就是对您的 DBIO 事务进行排序并将第一个的结果传递给第二个:
val insertDBIO = for {
fooId <- (fooTable returning fooTable.map(_id)) += Foo(None, "MyName", 42)
barId <- (barTable returning batTable.map(_id)) += Bar(None, "MyBarname", fooId)
} yield (fooId, barId)
db.run(insertDBIO.transactionally)
transactionally
调用将确保两者 运行 在同一连接上。