public function move($delta, $where = '')
{
if (!$this->hasField('ordering')) {
throw new SpecialColumnMissing(sprintf('%s does not support ordering.', $this->tableName));
}
$this->triggerEvent('onBeforeMove', array(&$delta, &$where));
$ordering_field = $this->getFieldAlias('ordering');
// If the change is none, do nothing.
if (empty($delta)) {
$this->triggerEvent('onAfterMove');
return $this;
}
$k = $this->idFieldName;
$row = null;
$db = $this->getDbo();
$query = $db->getQuery(true);
// If the table is not loaded, return false
if (empty($this->{$k})) {
throw new RecordNotLoaded(sprintf("Model %s does not have a loaded record", $this->getName()));
}
// Select the primary key and ordering values from the table.
$query->select(array($db->qn($this->idFieldName), $db->qn($ordering_field)))->from($db->qn($this->tableName));
// If the movement delta is negative move the row up.
if ($delta < 0) {
$query->where($db->qn($ordering_field) . ' < ' . $db->q((int) $this->{$ordering_field}));
$query->order($db->qn($ordering_field) . ' DESC');
} elseif ($delta > 0) {
$query->where($db->qn($ordering_field) . ' > ' . $db->q((int) $this->{$ordering_field}));
$query->order($db->qn($ordering_field) . ' ASC');
}
// Add the custom WHERE clause if set.
if ($where) {
$query->where($where);
}
// Select the first row with the criteria.
$row = $db->setQuery($query, 0, 1)->loadObject();
// If a row is found, move the item.
if (!empty($row)) {
// Update the ordering field for this instance to the row's ordering value.
$query = $db->getQuery(true)->update($db->qn($this->tableName))->set($db->qn($ordering_field) . ' = ' . $db->q((int) $row->{$ordering_field}))->where($db->qn($k) . ' = ' . $db->q($this->{$k}));
$db->setQuery($query)->execute();
// Update the ordering field for the row to this instance's ordering value.
$query = $db->getQuery(true)->update($db->qn($this->tableName))->set($db->qn($ordering_field) . ' = ' . $db->q((int) $this->{$ordering_field}))->where($db->qn($k) . ' = ' . $db->q($row->{$k}));
$db->setQuery($query)->execute();
// Update the instance value.
$this->{$ordering_field} = $row->{$ordering_field};
}
$this->triggerEvent('onAfterMove');
return $this;
}