光滑3.0选择然后插入

时间:2015-09-21 10:50:58

标签: scala slick-3.0

如果该行存在,我想插入一个具有不同状态值的新行,并将新实例作为Some返回给调用者。如果它不存在,则没有任何反应并返回None。我拥有的是

 def revoke(name: String, issueFor: String): Future[MyLicense] = {
   val retrieveLicense = slickLicenses.filter(l => l.name === name && l.issueFor === issueFor).
  sortBy(_.modifiedOn.desc).result.headOption
   val insertLicense = for {
     licenseOption <- retrieveLicense
   } yield {
     licenseOption match {
       case Some(l) => Some(slickLicenses += l.copy(status = RevokedLicense))
       case None => None
   }
 }
 db.run(insertLicense).map {r => 
   r.map { dbLicense => MyLicense(dbLicense.name, dbLicense.status)
 }

}

我该如何解决这个问题?

修改1

我将代码更改为

override def revoke(name: String, issueFor: String): Future[String] = {
  val retrieveLicense = slickLicenses.filter(l => l.name === name && l.issueFor === issueFor).
  sortBy(_.modifiedOn.desc).result.headOption
  val insertLicenseAction = for {
    l <- retrieveLicense
    newLicense <- slickLicenses += l.get.copy(status = RevokedLicense)
} yield newLicense
  db.run(insertLicenseAction).map(_ => name)

}

因此,问题会改变我如何获取插入数据库的实例?感谢

1 个答案:

答案 0 :(得分:1)

这就是我最后所做的,

override def revoke(name: String, issueFor: String): Future[String] = {
val retrieveLicense = slickLicenses.filter(l => l.name === name && l.issueFor === issueFor).
    sortBy(_.modifiedOn.desc).result.headOption
val insertLicenseAction = for {
  l <- retrieveLicense
  _ <- l.map(x => slickLicenses += x.copy(status = RevokedLicense, 
             modifiedOn = new Timestamp(System.currentTimeMillis())))
    .getOrElse(DBIO.successful(l))
} yield ()
db.run(insertLicenseAction).map(x => name)}