在Slick中根据Id选择单行

时间:2013-05-09 11:59:01

标签: scala slick scalaquery

我想根据Id查询用户的单行。我有以下虚拟代码

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))
  }
}

在我看来,findById查询单个列是一种过度杀伤,因为Id是标准主键。有谁知道更好的方法?请注意我正在使用Play! 2.1.0

5 个答案:

答案 0 :(得分:15)

在Slick 3中使用headOption方法。*:

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

答案 1 :(得分:7)

您可以从list切换到firstOption,从功能中删除两行。这看起来像这样:

def findById(userId: Int)(implicit session: Session): Option[User] = {
  val user = this.map { e => e }.where(u => u.id === userId).take(1)
  user.firstOption
}

我相信你也会这样做你的查询:

def findById(userId: Int)(implicit session: Session): Option[User] = {
  val query = for{
    u <- Users if u.id === userId
  } yield u
  query.firstOption
}

答案 2 :(得分:4)

firstOption是一种方法,是的。

具有

  val users: TableQuery[Users] = TableQuery[Users]

我们可以写

def get(id: Int): Option[User] = users.filter { _.id === id }.firstOption

答案 3 :(得分:0)

答案较短。

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

答案 4 :(得分:0)

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
相关问题