Select single row based on Id in Slick

13.9k Views Asked by At

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

5

There are 5 best solutions below

0
On
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
2
On

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
}
0
On

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
0
On

A shorter answer.

  `def findById(userId: Int)(implicit session: Session): Option[User] = {
     User.filter(_.id === userId).firstOption
        }`
1
On

Use headOption method in Slick 3.*:

  def findById(userId: Int): Future[Option[User]] ={
    db.run(Users.filter(_.id === userId).result.headOption)
  }