scalafunctional-programmingslick-3.0playframework-2.6play-slick

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


I am new to play framework. I am working on a play slick based application where I want to fetch a list of objects from DB which will contains some selected fields. For fetching all the fields I am using following code:

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)
    }
  }

So my question is how to fetch only timeStamp, toUserID, mailContent, fromID, toID fields as the list of objects like UserMessage(timeStamp: Long, toUserID: String, mailContent: String, fromID: String, toID: String). I tried searching about this but didn't get any convincing answers.


Solution

  • Like I said in the comment you can do this:

    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)
        }
      }
    

    You can get rid of that Await.result

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

    Hope it helps.