如何将查询结果转换为案例类? [英] How to convert query result to case class?
本文介绍了如何将查询结果转换为案例类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Slick 2.0,并且具有以下User
案例类:
I'm using Slick 2.0 and I have the following User
case class:
case class User(id: Option[Long], email: String, password: String)
class Users(tag: Tag) extends Table[User](tag, "user") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def email = column[String]("email")
def password = column[String]("password")
def * = (id.?, email, password) <> ((User.apply _).tupled, User.unapply _)
}
并且我具有以下功能来通过用户的数据库ID吸引用户:
and I have the following function getting a user via their database id:
def findOneById(id: Long) = DB.withSession { implicit session =>
val result = (for {
u <- users if u.id === id
} yield (u.id, u.email, u.password)).first
User(Option(result._1), result._2, result._3)
}
是否有更简单的方法将Seq响应转换回result
到User
案例类?
Is there an easier way to convert the Seq response back result
into the User
case class?
推荐答案
好,我找到了答案.我部分来自@benji,部分来自这篇文章:将scala.slick.lifted.Query转换为案例类.
Ok, I found my answer. I got it in part from @benji and in part from this post: Converting scala.slick.lifted.Query to a case class.
以下而不是使用for理解,它返回了Option [User],这正是我所需要的:
Instead of using a for comprehension, the following returns an Option[User], which is exactly what I need:
def findOneById(id: Long):Option[User] = DB.withSession { implicit session =>
users.filter(_.id === id).firstOption
}
这篇关于如何将查询结果转换为案例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文