From b64ec89d67ef22897206d7061c86c53e2f6f9458 Mon Sep 17 00:00:00 2001 From: Peter Rotich <peter@enhancesoft.com> Date: Wed, 2 May 2018 17:55:39 +0000 Subject: [PATCH] Sorting: Alternative Data Source COALESCE sort fields when a column has multiple data sources. --- include/class.orm.php | 2 +- include/class.queue.php | 33 ++++++++++++++++++++++++++++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/include/class.orm.php b/include/class.orm.php index acb948534..733b880ea 100644 --- a/include/class.orm.php +++ b/include/class.orm.php @@ -1443,7 +1443,7 @@ class QuerySet implements IteratorAggregate, ArrayAccess, Serializable, Countabl if (!is_array($annotations)) $annotations = func_get_args(); foreach ($annotations as $name=>$A) { - if ($A instanceof SqlAggregate) { + if ($A instanceof SqlFunction) { if (is_int($name)) $name = $A->getFieldName(); $A->setAlias($name); diff --git a/include/class.queue.php b/include/class.queue.php index 189a7a846..950bff75c 100644 --- a/include/class.queue.php +++ b/include/class.queue.php @@ -2072,18 +2072,41 @@ extends VerySimpleModel { } function applySort($query, $reverse=false) { - $root = ($q = $this->getQueue()) ? $q->getRoot() : 'Ticket'; + $root = ($q = $this->getQueue()) ? $q->getRoot() : 'Ticket'; $fields = CustomQueue::getSearchableFields($root); + + $keys = array(); if ($primary = $fields[$this->primary]) { list(,$field) = $primary; - $query = $field->applyOrderBy($query, $reverse, - CustomQueue::getOrmPath($this->primary, $query)); + $keys[] = array(CustomQueue::getOrmPath($this->primary, $query), + $field); } + if ($secondary = $fields[$this->secondary]) { list(,$field) = $secondary; - $query = $field->applyOrderBy($query, $reverse, - CustomQueue::getOrmPath($this->secondary, $query)); + $keys[] = array(CustomQueue::getOrmPath($this->secondary, + $query), $field); + } + + if (count($keys) > 1) { + $fields = array(); + foreach ($keys as $key) { + list($path, $field) = $key; + $fields[] = new SqlField($path); + } + + $alias = sprintf('C%d', $this->getId()); + $expr = call_user_func_array(array('SqlFunction', 'COALESCE'), + $fields); + $query->annotate(array($alias => $expr)); + + $reverse = $reverse ? '-' : ''; + $query = $query->order_by("{$reverse}{$alias}"); + } else { + list($path, $field) = $keys[0]; + $query = $field->applyOrderBy($query, $reverse, $path); } + return $query; } -- GitLab