光滑和按选项列过滤 [英] Slick and filtering by Option columns
问题描述
我正在尝试使用 Scala Slick 1.0.1 过滤可选日期列.
I'm trying to filter against an optional date column with Scala Slick 1.0.1.
可能我只是没看到,但我有一张看起来像这样的桌子:
It may be I just don't see it, but I've got a table that looks something like this:
case class UserRole(id:UUID, userID:UUID, role:String)
object UserRole extends Table[UserRole]("User_Role") {
//(id: Long = 0l, name: String, active: Boolean) extends KeyedEntity[Long] {
def id = column[UUID]("ID", O.PrimaryKey)
def userID = column[UUID]("user_id")
def vendorID = column[UUID]("vendor_id")
def role = column[String]("role")
def user = foreignKey("user_FK", userID, User)(_.id)
def start = column[java.sql.Date]("startDate")
def endDate = column[Option[java.sql.Date]]("endDate")
def * = id ~ userID ~ role <> (UserRole.apply _, UserRole.unapply _)
}
您会在那里看到 endDate 是可选的.
You'll see there that the endDate is optional.
如何构造一个查询,在其中进行过滤,以便 endDate 可以为 NULL/None 或大于当前 (db) 日期?仅供参考,我通常使用嵌入式 api
How do I construct a query where I filter so endDate can be NULL/None or greater than the current (db) date? FYI, I'm generally using the embedded api
谢谢
推荐答案
这不是很好(关于 null.asInstanceOf
的部分),但我认为它会起作用.我从一个旧的 Scala 查询帖子中得到了这个想法,所以我不知道 slick 是否为此提供了更好的东西,但是当我查看查询的结果 selectStatement
时,它看起来是正确的:
This is not pretty (the part about null.asInstanceOf
), but I think it will work. I got that idea from an old Scala Query post, so I don't know if slick ever put something better in for that, but when I looked at the resulting selectStatement
from the query, it looked correct:
val now = new java.sql.Date(System.currentTimeMillis())
val query = for {
role <- UserRole
if (role.endDate === null.asInstanceOf[Option[java.sql.Date]] || role.endDate > now)
} yield role
编辑
感谢@MartinKolinek 的评论,这段代码也可以工作,而且更简洁,可能是更好的做事方式:
Thanks to the comment by @MartinKolinek, this code will also work and is much cleaner and probably the better way to do things:
val now = new java.sql.Date(System.currentTimeMillis())
val query = for {
role <- UserRole
if (role.endDate.isNull || role.endDate > now)
} yield role
这篇关于光滑和按选项列过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!