Scala/slick: 如果不存在则获取插入行的id

Scala/slick: Get the id of row inserted if not exists already

我正在尝试使用这段代码插入-if-not-exists

case class Item(name: String, id: Long = 0L) // name is unique

val data = Query("Bob")
val exists = items.filter(_.name === "Bob").exists
val sel = data.filterNot(_ => exists)
val action = items.map(_.name).forceInsertQuery(sel)

它有效,但我想 return 行的 ID(现有/插入)。目前它 return 是一个布尔值。如何获取 id 而无需再次查询?

如果 idprimary keyauto increment 那么您可以在同一个插入查询中 return 和 id。如果没有,那是不可能的。

val tableQuery = TableQuery[Items] //items is a slick table

def getIdAfterInsert(item: Item): DB[Long] = {
  tableQuery.filter(_.name === item.name).take(1).result.headOption.flatMap {
    case Some(dbItem) =>
      DBIO.successful(dbItem.id)
    case None =>
     tableQuery.returning(tableQuery.map(_.id)) += item 
  }
}

但是如果 id 不是 primary keyauto increment 那么你必须这样做。

def getIdAfterInsert(item: Item): DBIO[Long] = {
 tableQuery.filter(_.name === item.name).take(1).result.headOption {
  case Some(item) => DBIO.successful(item.id)
  case None => 
    (tableQuery += item).flatMap { _ => 
      tableQuery.filter(_.name === item.name).take(1).result.id //this is the extra query
    }
 }
}