Slick:选项列过滤

时间:2014-10-24 18:40:13

标签: scala slick slick-2.0

我想做这样的事情(这是一个简化实际问题的简化示例):

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

由于最后一个“真实”,因此无法编译。有没有更好的方法呢?

2 个答案:

答案 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种情况:

  1. isMale已定义并等于Some(true)

    结果SQL:select * from people when (name is not null) and (wife is not null);

  2. isMale已定义并等于Some(false)

    结果SQL:select * from people when (name is not null) and (wife is null);

  3. isMale为空

    结果SQL:select * from people when name is not null;