scala 根据 Slick 中的 Id 选择单行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16461260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select single row based on Id in Slick
提问by Khalid Saifullah
I want to query a single row from user based on Id. I have following dummy code
我想根据 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))
}
}
It seems to me that findByIdis 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
在我看来,findById查询单个列是一种矫枉过正,因为 Id 是标准主键。有人知道更好的方法吗?请注意,我正在使用 Play!2.1.0
回答by Saeed Zarinfam
Use headOptionmethod in Slick 3.*:
headOption在 Slick 3.* 中使用方法:
def findById(userId: Int): Future[Option[User]] ={
db.run(Users.filter(_.id === userId).result.headOption)
}
回答by cmbaxter
You could drop two lines out of your function by switching from listto firstOption. That would look like this:
通过从 切换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
}
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
}
回答by tuxSlayer
firstOptionis a way to go, yes.
firstOption是一条路,是的。
Having
拥有
val users: TableQuery[Users] = TableQuery[Users]
we can write
我们可以写
def get(id: Int): Option[User] = users.filter { _.id === id }.firstOption
回答by binkabir
A shorter answer.
一个简短的答案。
`def findById(userId: Int)(implicit session: Session): Option[User] = {
User.filter(_.id === userId).firstOption
}`
回答by Goku__
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

