/** * Change the ordering of the records of the table * * @param string $where The WHERE clause of the SQL used to fetch the order * * @return boolean True is successful * * @throws UnexpectedValueException */ public function reorder($where = '') { if (!$this->onBeforeReorder($where)) { return false; } // If there is no ordering field set an error and return false. $order_field = $this->getColumnAlias('ordering'); if (!in_array($order_field, $this->getKnownFields())) { throw new UnexpectedValueException(sprintf('%s does not support ordering.', $this->_tbl_key)); } $k = $this->_tbl_key; // Get the primary keys and ordering values for the selection. $query = $this->_db->getQuery(true); $query->select($this->_tbl_key . ', ' . $this->_db->qn($order_field)); $query->from($this->_tbl); $query->where($this->_db->qn($order_field) . ' >= ' . $this->_db->q(0)); $query->order($this->_db->qn($order_field)); // Setup the extra where and ordering clause data. if ($where) { $query->where($where); } $this->_db->setQuery($query); $rows = $this->_db->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 = $this->_db->getQuery(true); $query->update($this->_tbl); $query->set($this->_db->qn($order_field) . ' = ' . $this->_db->q($i + 1)); $query->where($this->_tbl_key . ' = ' . $this->_db->q($row->{$k})); $this->_db->setQuery($query); $this->_db->execute(); } } } $result = $this->onAfterReorder(); return $result; }