问题
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