FOF30\Model\DataModel::reorder PHP Method

reorder() public method

Change the ordering of the records of the table
public reorder ( string $where = '' ) : static
$where string The WHERE clause of the SQL used to fetch the order
return static Self, for chaining
    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;
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * Change the ordering of the records of the table
  *
  * @param   string $where The WHERE clause of the SQL used to fetch the order
  *
  * @return  static  Self, for chaining
  *
  * @throws  \UnexpectedValueException
  */
 public function reorder($where = '')
 {
     if (empty($where)) {
         $where = $this->getReorderWhere();
     }
     return parent::reorder($where);
 }