Skip to content

Instantly share code, notes, and snippets.

@eberfreitas
Created December 4, 2009 19:00
Show Gist options
  • Save eberfreitas/249256 to your computer and use it in GitHub Desktop.
Save eberfreitas/249256 to your computer and use it in GitHub Desktop.
Simple function to enable sorting on the model
<?php
class AppModel extends Model {
public function sort($ids, $orderField = 'order') {
if ($ids && is_array($ids)) {
$count = count($ids);
$query = array();
$query[] = "UPDATE `{$this->table}`";
$query[] = "SET `{$orderField}` = CASE `{$this->primaryKey}`";
for ($i = 0; $i < $count; $i++) {
$position = $i + 1;
$query[] = "WHEN {$ids[$i]} THEN {$position}";
}
$query[] = "END";
$query[] = "WHERE `{$this->primaryKey}` IN (";
$query[] = implode(", ", $ids);
$query[] = ")";
return $this->query(implode(" ", $query));
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment