2016-07-09 66 views
1

我想只在行有有效數據的情況下更新行中的某一列。具體來說:我有一個Event表,其中start,stopisActive旗號。 我想通過設置isActivetrue激活一些Events,但是我需要檢查開始和結束日期是否有效。 型號:只有條件滿足時才更新行

case class Event {start:DateTime, stop:DateTime, isActive:Boolean} 

我的驗證方法簽名:

validateEvent(ev: Event): Boolean 

我的第一種方法:

def activateEv() = Action.async(parse.json) { request => { ... val ev = db.run(dao.findEvById(poid, uid)) val ret = ev.flatMap { case st: Option[Event] => if (validateEvent(st.get)) { db.run(dao.updateActivity(poid, true).map { case 0 => false case other => true } } else Future(false) } ... } }

我認爲這是沒有辦法的辦法這個問題應如何解決。 你能建議嗎? 也許只有一個db.run就足夠了?

回答

2

這可以在單個db.run中使用組合器(例如flatMap)在DBIOAction對象上實現。假設你dao方法看起來像:

case object dao { 
    def findEvById(poid: Int, uid: Int): DBIOAction[Option[Event], NoStream, Effect.Read] = ??? 

    // In your case `updateActivity` returns an `Int` and you're mapping it to a `Boolean`. 
    // That mapping could be placed here, so `updateActivity` would return `Boolean` now. 
    def updateActivity(poid: Int, bool: Boolean): DBIOAction[Boolean, NoStream, Effect.Write] = ??? 
} 

這是我們如何能夠達到你要尋找的東西:

... 
val action = dao.findEvById(poid, uid).flatMap { 
    case Some(event) if validateEvent(event) => dao.updateActivity(poid, true) 
    case _ => DBIO.successful(false) 
}.transactionally 

db.run(action) 
... 

如你所見,我們在這裏有一個交易,這將使一選擇後進行更新(僅當event有效時)。此外,整個select then update行動可能是您的dao中的一個單獨的方法。

相關問題