我想做这样的事情(这是一个简化实际问题的简化示例):
def findByGender(isMale: Option[Boolean]) = {
People.filter(row => row.name.isNotNull && isMale match {
case Some(true) => row.wife.isNotNull // find rows where wife column is not null
case Some(false) => row.wife.isNull // find rows where wife column is null
case None => true // select everything
})
}
由于最后一个“真实”,因此无法编译。有没有更好的方法呢?
答案 0 :(得分:4)
您必须将其设为Column[Boolean]
:
def findByGender(isMale: Option[Boolean]) = {
People.filter(row => row.name.isNotNull && isMale match {
case Some(true) => row.wife.isNotNull // find rows where wife column is not null
case Some(false) => row.wife.isNull // find rows where wife column is null
case None => LiteralColumn(true) // select everything
})
}
答案 1 :(得分:0)
如果您使用的是Slick 3.3.x,则可以使用以下解决方案:
def findByGender(isMale: Option[Boolean]) =
People
.filter(_.name.isDefined)
.filterIf(isMale == Some(true))(_.wife.isDefined)
.filterIf(isMale == Some(false))(_.wife.isEmpty)
或
def findByGender(isMale: Option[Boolean]) =
People
.filter(_.name.isDefined)
.filterOpt(isMale) {
case (row, true) => row.wife.isDefined
case (row, false) => row.wife.isEmpty
}
有3种情况:
isMale
已定义并等于Some(true)
结果SQL:select * from people when (name is not null) and (wife is not null);
isMale
已定义并等于Some(false)
:
结果SQL:select * from people when (name is not null) and (wife is null);
isMale
为空
结果SQL:select * from people when name is not null;