Reputation: 747
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
Upvotes: 12
Views: 13994
Reputation: 10180
Use headOption
method in Slick 3.*:
def findById(userId: Int): Future[Option[User]] ={
db.run(Users.filter(_.id === userId).result.headOption)
}
Upvotes: 19
Reputation: 970
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.apply _, User.unapply _)
// .? in the above line for Option[]
val byId = createFinderBy(_.id)
def findById(id: Int)(implicit session: Session): Option[User] = user.byId(id).firstOption
Upvotes: 0
Reputation: 154
A shorter answer.
`def findById(userId: Int)(implicit session: Session): Option[User] = {
User.filter(_.id === userId).firstOption
}`
Upvotes: 0
Reputation: 2824
firstOption
is a way to go, yes.
Having
val users: TableQuery[Users] = TableQuery[Users]
we can write
def get(id: Int): Option[User] = users.filter { _.id === id }.firstOption
Upvotes: 3
Reputation: 35453
You could drop two lines out of your function by switching from list
to firstOption
. That would look like this:
def findById(userId: Int)(implicit session: Session): Option[User] = {
val user = this.map { e => e }.where(u => u.id === userId).take(1)
user.firstOption
}
I believe you also would do your query like this:
def findById(userId: Int)(implicit session: Session): Option[User] = {
val query = for{
u <- Users if u.id === userId
} yield u
query.firstOption
}
Upvotes: 6