Reputation: 742
I am writing a dropwizard application using kotlin and one of the resource methods will receives multiple parameters(email, phone, is_deleted, etc). Based on the incoming query params, I have to filter the table. I am using DAO API of Exposed to construct the query.
val result = User.find { //SqlExpressionBuilder
Users.isDeleted eq false
Users.email eq "[email protected]"
}.sortedByDescending { it.createdAt }
How to add multiple where conditions to the query based on the map of query params using a for in loop?
Upvotes: 1
Views: 2802
Reputation: 546
It is possible:
val email = URLDecoder.decode("email", "UTF-8")
val phone = URLDecoder.decode("phone", "UTF-8")
Users.find {
if (email != null) (Users.email eq email) else Op.TRUE
.and(if (phone != null) (Users.phone eq phone) else Op.TRUE)
}
Upvotes: 0
Reputation: 742
I had to solve the problem using DSL. Seems like DAO doesn't have such provision to create such adhoc query.
val query = Users.selectAll()
for((k, v) in params) {
val value = URLDecoder.decode(v, "UTF-8")
when(value) {
"email" -> query.andWhere { Users.email eq value }
"phone" -> query.andWhere { Users.phone eq value }
}
}
return query.andWhere { Users.isDeleted.eq(false) }
As @Tapac mentioned, one can use User.wrapRows(query).sortedByDescending()
also to frame such query but again one have to use DSL.
Hope that helps someone.
Upvotes: 1