Play Slick:如何在 play-slick 3.0.0 中从数据库 table 中获取选定的字段?

Play Slick: How to fetch selected fields from a DB table in play-slick 3.0.0?

我是玩框架的新手。我正在开发一个基于 play slick 的应用程序,我想从 DB 中获取一个对象列表,其中将包含一些选定的字段。为了获取我使用以下代码的所有字段:

case class Mail(txID: String,
               timeStamp: Long,
               toUserID: String,
               mailContent: String,
               mailTemplateFileName: String,
               fromID: String,
               toID: String
               )
def getLogFromIDFuture(userID: String): Future[Option[List[Mail]]] = cache.getOrElseUpdate[Option[List[Mail]]](userID) {
    val resultingUsers = db.run(mailsData.filter(x => x.toUserID === userID).result)
    val res = Await.result(resultingUsers, Duration.Inf)
    res.map(t => t) match {
      case t if t.nonEmpty =>
        Future(Some(t.toList))
      case _ => Future(None)
    }
  }

所以我的问题是如何只获取 timeStamp、toUserID、mailContent、fromID、toID 字段作为对象列表,如 UserMessage(timeStamp: Long, toUserID: String, mailContent: String, fromID: String, toID: String)。我试着搜索这个但没有得到任何令人信服的答案。

正如我在评论中所说,您可以这样做:

def getLogFromIDFuture(userID: String): Future[Option[List[UserMessage]]] = cache.getOrElseUpdate[Option[List[Mail]]](userID) {
    val resultingUsers = db.run(mailsData.filter(x => x.toUserID === userID).map(entry =>(entry.timeStamp, entry.toUserID, entry.mailContent, entry.fromID, entry.toID))
.result)// here you have the tuple of things
// add the mapping of the tuple to the UserMessage
    val res = Await.result(resultingUsers, Duration.Inf)
    res.map(t => t) match {
      case t if t.nonEmpty =>
        Future(Some(t.toList))
      case _ => Future(None)
    }
  }

你可以去掉那个Await.result

    resultingUsers.map( match {
      case t if t.nonEmpty =>
       Some(t.toList)
      case _ => None
     }
)

希望对您有所帮助。