Created
December 4, 2009 19:00
-
-
Save eberfreitas/249256 to your computer and use it in GitHub Desktop.
Simple function to enable sorting on the model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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