I want to query a single row from user based on Id. I have following dummy code
case class User(
id: Option[Int],
name: String
}
object Users extends Table[User]("user") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def * = id ~ name <>(User, User.unapply _)
def findById(userId: Int)(implicit session: Session): Option[User] = {
val user = this.map { e => e }.where(u => u.id === userId).take(1)
val usrList = user.list
if (usrList.isEmpty) None
else Some(usrList(0))
}
}
It seems to me that findById
is a overkill to query a single column as Id is standard primary key. Does anyone knows any better ways? Please note that I am using Play! 2.1.0
Use headOption
method in Slick 3.*:
def findById(userId: Int): Future[Option[User]] ={
db.run(Users.filter(_.id === userId).result.headOption)
}