public function reorder($where = '')
{
// If there is no ordering field set an error and return false.
if (!$this->hasField('ordering')) {
throw new SpecialColumnMissing(sprintf('%s does not support ordering.', $this->tableName));
}
$this->triggerEvent('onBeforeReorder', array(&$where));
$order_field = $this->getFieldAlias('ordering');
$k = $this->getIdFieldName();
$db = $this->getDbo();
// Get the primary keys and ordering values for the selection.
$query = $db->getQuery(true)->select($db->qn($k) . ', ' . $db->qn($order_field))->from($db->qn($this->getTableName()))->where($db->qn($order_field) . ' >= ' . $db->q(0))->order($db->qn($order_field) . 'ASC, ' . $db->qn($k) . 'ASC');
// Setup the extra where and ordering clause data.
if ($where) {
$query->where($where);
}
$rows = $db->setQuery($query)->loadObjectList();
// Compact the ordering values.
foreach ($rows as $i => $row) {
// Make sure the ordering is a positive integer.
if ($row->{$order_field} >= 0) {
// Only update rows that are necessary.
if ($row->{$order_field} != $i + 1) {
// Update the row ordering field.
$query = $db->getQuery(true)->update($db->qn($this->getTableName()))->set($db->qn($order_field) . ' = ' . $db->q($i + 1))->where($db->qn($k) . ' = ' . $db->q($row->{$k}));
$db->setQuery($query)->execute();
}
}
}
$this->triggerEvent('onAfterReorder');
return $this;
}