Instead of splitting filter clauses to where and having parts before adding them to query.where or query.having, add all filter clauses to query.where, and when compiling the query split the where to having and where parts.