Slick dynamically filter by a list of columns and values

别等时光非礼了梦想. 提交于 2020-06-29 06:11:51

问题


I'm trying to create a query in slick with dynamic filtering. I have a Seq[(String, String)] where the first element of the tuple is the column name while the second is the value against which make the filter.

In pseudo code, I want to do something like this:

val filters: Seq[(String, String)]
val query = filters.foldLeft(entityTable) {
    case(query, (column, value)) => query.filter(select(column) === value)
}

I already have a function def select(name: String): Rep[_] that returns the column Rep starting from its name that works well but I don't know how to get all the implicits needed to make the === function (or others comparison functions) work.

Is there any way to make such a dynamic filtering in slick?


回答1:


Yes there is !

I use this method

private def applyOperator[T](left: Rep[T], right: Rep[T], operator: String)(implicit om: OptionMapper2[T, T, Boolean, T, T, Boolean]): Rep[Boolean] = {
    operator match {
      case "==" => new BaseColumnExtensionMethods(left) === right
      case "!=" => new BaseColumnExtensionMethods(left) =!= right
      case "like" => new StringColumnExtensionMethods(left.asInstanceOf[Rep[String]]) like right.asInstanceOf[Rep[String]] //Breaks if T is not String
    }
  }

Then you can write something like

val filters: Seq[(String, String)]
val query = filters.foldLeft(entityTable) {
    case(query, (column, value)) => query.filter(applyOperator(yourFunctionForColumnFromName(column),value, "=="))
}


来源:https://stackoverflow.com/questions/53224182/slick-dynamically-filter-by-a-list-of-columns-and-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!