Slick 3.0 基于条件更新行

Slick 3.0 Update Row Based on a Condition

我有以下方法实际根据 table 更新数据库行。它首先检查一个条目是否存在并具有特定条件,只有当它存在时,它才会更新相应的行。如此有效,对数据库进行了两次调用。我想避免将两个调用发送到数据库。所以这是代码:

  def confirmUserRegistration(hash: String) = async {
    val query = UserRegistrationTable.registrationForHash(hash)
    val isRowAvailable = await(database.run(query.result.headOption))
    if (isRowAvailable.isDefined) {
      // do the update
    } else {
    // do nothing and return
    }
  }

UserRegistrationTable.registrationForHash(哈希)查询如下所示:

  object UserRegistrationTable {

    val all = TableQuery[UserRegistrationTable]

    val registrationForHash = (hash: String) => {
      all.filter(_.registrationHash === hash)
    }
  }

那么我该如何优化我的服务以仅对数据库发出一次调用?

编辑:更新了下面 post 给出的反馈:

下面是我的方法:

  def confirmUserRegistration(hash: String) = async {
    val query = {
      UserRegistrationTable.registrationForHash(hash)
        .map(_.hasUserConfirmed)
        .update(true)
    }

    val isUpdated: Int = await(database.run(query))

  }

只需使用以下更新:

val updateOperation: DBIO[Int] = all
    .filter(_.registrationHash === hash)
    .map(u => (u.field1, u.field2, u.field3))
    .update((newValue1, newValue2, newValue3))

请注意上面的 updateResultDBIO 包含 Int - 更新的行数。

所以你可以这样做:

db.run(updateOperation).map { updatedRows =>
     if(updatedRows >= 0) {
         // at least one row was affected, return something here
     } else {
         // nothing got updated, return something here
     }
}

如果您想更新整行,您可以使用您的案例 class 但我怀疑这就是您想要的:

val userRegistration: UserRegistrationCaseClass = ...

val updateOperation: DBIO[Int] = all
    .filter(_.registrationHash === hash)
    .update(newUserRegistration)