Scala用于理解Slick Query

时间:2015-08-10 11:37:30

标签: scala playframework slick playframework-2.4

我是Scala的新手,我正在构建一个Play应用来学习Scala和Slick。该应用程序有待办事项列表,每个列表都有项目。每个用户都有多个列表。我编写了一个控制器来将列表作为JSON,而JSON包含列表中的所有项目。

arr = {2, 1,3 } 
rank will be {1,0 ,2}

是否可以使用for comprehension编写此函数?我有一个嵌套的flatMap + map调用,所以看起来应该是可能的。

1 个答案:

答案 0 :(得分:2)

是的,有可能。像这样:

def viewList(id: Long) = AuthenticatedAction.async { implicit request =>
  val userId = request.user.toLong
  for {
    list <- db.run(todoLists.filter(listById(id, userId)).result.headOption)
    resp <- list.fold[Future[Result]](Future.successful(NotFound)) { _ =>
      val json = toJson(list).as[JsObject]
      // Fetch the items in this list and add them to the JSON response
      db.run(todoItems.filter(_.listId === id).sortBy(_.text).result).map { items => 
        Ok(json + ("items" -> toJson(items)))
      }
    }
  } yield resp 
}

另一种变体:

  def viewList(id: Long) = AuthenticatedAction.async { implicit request =>
    val userId = request.user.toLong
    for {
      list <- db.run(todoLists.filter(listById(id, userId)).result.headOption)
      items <- db.run(todoItems.filter(_.listId === id).sortBy(_.text).result)
    } yield list match {
      case Some(_) => Ok(toJson(list).as[JsObject] + ("items" -> toJson(items)))
      case None => NotFound
    }
  }