2

我有一个简单的 MySQL 数据库,在 REG_PERIODS 表中有一行。当我运行这个查询时,我得到了该行。

val getRegPeriodAction = regPeriods.sortBy(_.endDate).result.head.map { regPeriod ⇒
  Logger.debug(s"regPeriod = ${regPeriod}")

  regPeriod
}

但是,当我运行此查询时,我什么也没得到,实际上甚至没有到达调试消息!

val getRegPeriodAction = regPeriods.sortBy(_.endDate).result.headOption.map { regPeriodOption ⇒
  Logger.debug(s"regPeriodOption = ${regPeriodOption}")

  regPeriodOption match {
    case Some(regPeriod) ⇒ regPeriod
  }
}

我正在使用 play-slick 1.0.0。我在这里误解了什么吗?使用 headOption 时我应该收到 Some(regPeriod) 吗?

编辑

我尝试运行headOption查询db.run( ... )并将结果发送到另一个函数,如下所示:

def handleResult(opt: Option[RegistrationPeriod]) {
  Logger.debug(s"received $opt")
}

for {
  r <- db.run( regPeriods.sortBy(_.endDate.desc).result.headOption )
  _ <- handleResult( r )
} ...

奇怪的是,handleResult 从来没有被调用过!一旦我将代码更改为调用head而不是headOption一切都按预期工作。

4

1 回答 1

4

.result不在数据库上执行您的查询。它创建了一个必须传递给它db.run()db.stream()为了执行它的操作:

val action = regPeriods.sortBy(_.endDate).result.headOption
val result: Future[Option[RegPeriod]] = db.run(action)

// accessing your data
result.map(r => r....)  // r is of type Option[RegPeriod]
于 2015-07-24T14:57:23.753 回答