根据SLICK中的ID选择单行 [英] Select single row based on Id in Slick
本文介绍了根据SLICK中的ID选择单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据ID查询USER中的一行。我有以下虚拟代码
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
推荐答案
在slick 3中使用headOption
方法。*:
def findById(userId: Int): Future[Option[User]] ={
db.run(Users.filter(_.id === userId).result.headOption)
}
这篇关于根据SLICK中的ID选择单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文