nette/database

Incosistency between HAVING and WHERE

dakujem opened this issue · 0 comments

Version: 2.x, 3.x

I was wondering why the two methods where and having were so inconsistent.
Why does having only accept a string, while where will happily accept an array of string as well?
All the while multiple calls to having will overwrite the HAVING condition, while multiple calls to where will add more WHERE conditions.

This I find suboptimal, as both HAVING and WHERE are similar in the way the resulting SQL is built.

I have a use case, where the condition is wrapped into a "filter instruction object", that comes from a filter form and upon reaching the DB layer it is translated to SQL. Depending on the particular filtering setting, groupping and stuff can be activated, which is when some of the conditions need to be added into HAVING part of the SQL. Dealing with this inconsistency is laborous and defeats the purpose of database as a "smart" layer.

I would like the following pattern / pseudocode to be usable:

$filter = [
    'size' => 'big',
    'color' => 'red',
    'min-count' => 10,
    'min-value' => 500,
];
$query = $connection->select(...);
$map = [
    'min-count' => 'COUNT(`id`) ?',
    'min-value' => 'SUM(`price`) ?',
];
foreach ($filter as $subject => $value) {
    $mapped = $map[$subject] ?? null;
    if (!$mapped) {
        $query->where("%n ?", $subject, $value);
    } else {
        // this does not work as expected right now (gets overwritten)
        $query->having($mapped, $value);
    }
}