问题
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)
}
As you can see, the problem is that currentPropId
is of type Rep[Option[Long]]
and of course Property
needs a proper Long
instead.
For the languageId it sufficed to add a result
to the query (languages.all filter (_.code === languageCode)).result.head
But for the currentPropId
the type then still is of FixedSqlAction
edit:
Trying it like this
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
}
Does not work, because that's not a Seq[DBIOAction]
anymore but a Seq[Object]
(Not Any
, but Object
)
回答1:
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
}
}
...
来源:https://stackoverflow.com/questions/47126176/how-to-get-maxid-of-table-repoptionlong-for-subsequent-insert-without-c