Khalid Saifullah
Khalid Saifullah

Reputation: 747

Select single row based on Id in Slick

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

Answers (5)

Saeed Zarinfam
Saeed Zarinfam

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

Goku__
Goku__

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

binkabir
binkabir

Reputation: 154

A shorter answer.

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

Upvotes: 0

tuxSlayer
tuxSlayer

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

cmbaxter
cmbaxter

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

Related Questions