Select single row based on Id in Slick

坚强是说给别人听的谎言 提交于 2019-12-08 15:07:32

问题


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


回答1:


Use headOption method in Slick 3.*:

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



回答2:


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
}



回答3:


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



回答4:


A shorter answer.

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



回答5:


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


来源:https://stackoverflow.com/questions/16461260/select-single-row-based-on-id-in-slick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!