如何获取表= Rep [Option [Long]]的max(id)进行后续插入,而无需在之间调用db.run [英] How to get max(id) of table = Rep[Option[Long]] for subsequent insert, without calling db.run in between
问题描述
我在一个表中有一个插入,这取决于另一个表的最大ID。
I have an insert to a table, that depends on the max id of another table.
def add(languageCode: String,
typeId: Long,
properties: Seq[Property]): Unit = {
val dbAction = (
for{
nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
language <- (languages.all filter (_.code === languageCode)).result.head
_ <- DBIO.seq(properties.map
{
property =>
val id = property.id
val name = property.key
val value = property.value
if(id == 0) {
val currentPropId: FixedSqlAction[Option[Long], h2Profile.api.NoStream, Effect.Read] = this.properties.all.map(_.id).max.result
val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, currentPropId + 1, name)
nodeProperties.all += NodeProperty(nodeId, 2, value)
} else {
nodeProperties.all += NodeProperty(nodeId, id, value)
}
}: _*)
} yield()).transactionally
db.run(dbAction)
}
您可以看到,问题在于 currentPropId
的类型为 Rep [Option [Long]]
,当然,属性
需要一个正确的 Long
代替。
As you can see, the problem is that currentPropId
is of type Rep[Option[Long]]
and of course Property
needs a proper Long
instead.
对于languageId,足以添加结果
到查询(languages.all过滤器(_.code === languageCode))。result.head
For the languageId it sufficed to add a result
to the query (languages.all filter (_.code === languageCode)).result.head
但是对于 currentPropId
而言,类型仍然是 FixedSqlAction
But for the currentPropId
the type then still is of FixedSqlAction
编辑:
以这种方式尝试
if(id == 0) {
this.properties.all.map(_.id).max.map {
id =>
val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, id+1, name)
val nodeProperty = nodeProperties.all += NodeProperty(nodeId, 2, value)
propertyId andThen nodeProperty
}
不起作用,因为它不再是 Seq [DBIOAction]
而是 Seq [Object]
(不是 Any
,而是 Object
)
Does not work, because that's not a Seq[DBIOAction]
anymore but a Seq[Object]
(Not Any
, but Object
)
推荐答案
您不能将提升类型(Rep [_])与标准Scala类型混合使用。
您可以映射到 SqlAction
以提取所需的类型。
You cannot mix the lifted types (Rep[_]) with standard Scala types.
You can map over your SqlAction
to extract the needed type.
val currentPropId: FixedSqlAction[Option[Long], NoStream, Effect.Read] = ???
currentPropId.flatMap { id: Option[Long] =>
???
}
在您的情况下,类似这样:
In your exact case, something like this:
if(id == 0) {
properties.map(_.id).max.result.flatMap { id: Option[Long] =>
val propertyId = (properties returning properties.map(_.id)) += Property(language.id.get, id.map(_ + 1), name)
val nodeProperty = nodeProperties += NodeProperty(nodeId, 2, value)
propertyId andThen nodeProperty
}
}
...
这篇关于如何获取表= Rep [Option [Long]]的max(id)进行后续插入,而无需在之间调用db.run的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!