bgvoka bgvoka - 1 year ago 161
Scala Question

Dynamic OR filtering - Slick

Ok, I've got a method with multiple optional arguments like this

def(username: Option[String], petname: Option[String], favouritefood: Option[String])

and i want to write a dynamic query that will be capable of fetching the data of defined arguments in a way of this

select * from table where un like username or pn like pn or ff like ff;

so depending of which arguments are defined to add them to query with OR operator?

tfh tfh
Answer Source

Something like this should work. I had to use a similiar fragment in my own code and it is also close to what cvogt proposes in above comment (I think).

val username = Option("")
val petname = Option("")
val ff:Option[String] = None

val default = LiteralColumn(1) === LiteralColumn(1) 

yourTable.filter { it => 
  List( === _), === _), === _)
  ).collect({case Some(it)  => it}).reduceLeftOption(_ || _).getOrElse(default)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download