下面我的代码中的问题是所有子查询都不起作用(嵌套db.run)
我怀疑你最终会嵌套Future[R]
结果。不过我还没有调查过。因为...
从概念上讲,我没有得到什么?
我解决这个问题的方法是考虑结合DBIO[R]
。这可能是有帮助的概念。
你正在做的就是尝试运行每个action(查询、插入...)单独。
相反,将各个操作合并为一个操作并运行它。
我将主要逻辑重写为:
val action: DBIO[Int] = for {
existingEnterprise <- enterpriseQS.headOption
rowsAffected <- existingEnterprise match {
case Some(n) => salaries += new SalaryRow(0, n.id, salaryItem.worker)
case None => createNewEnterprise(salaryItem)
}
} yield rowsAffected
For the None
我会创建一个辅助方法:
def createNewEnterprise(salaryItem: SalaryItem): DBIO[Int] = for {
eId <- (enterprises returning enterprises.map(_.id)) += EnterpriseRow(0, salaryItem.enterpriseName)
rowsAffected <- salaries += new SalaryRow(0, eId, salaryItem.worker)
} yield rowsAffected
最后,我们可以运行:
val future: Future[Int] = db.run(action)
// or db.run(action.transactionally)
val result = Await.result(future, 2 seconds)
println(s"Result of action is: $result")
下半场我写的博客文章 http://underscore.io/blog/posts/2015/07/14/upsert.html更多地谈论这个。
我使用的代码是:https://github.com/d6y/so-31471590 https://github.com/d6y/so-31471590