Created
April 19, 2013 10:26
-
-
Save sime/5419482 to your computer and use it in GitHub Desktop.
Migrating from string to integer primary keys in CakePHP
This file contains hidden or 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 | |
App::uses('AppShell', 'Console/Command'); | |
class UserIdFromVarcharToInt extends CakeMigration { | |
public $description = ''; | |
public $migration = array( | |
'up' => array( | |
'alter_field' => array( | |
'users' => array( | |
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary', 'collate' => null, 'charset' => null), | |
), | |
), | |
), | |
'down' => array( | |
'alter_field' => array( | |
'users' => array( | |
'id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), | |
), | |
), | |
), | |
); | |
public function before($direction) { | |
if ($direction != 'up') { | |
return true; | |
} | |
$this->AppShell = new AppShell(); // For console output | |
$this->User = ClassRegistry::init('AppUser'); | |
$users = $this->User->find('all', array('fields' => 'id')); | |
if (empty($users)) { | |
return true; | |
} | |
$count = 1; | |
foreach($users as $user) { | |
$id = $user['AppUser']['id']; | |
$query = sprintf('UPDATE `users` SET `id` = %d WHERE `id` = \'%s\' LIMIT 1', $count, $id); | |
$this->User->query($query); | |
$this->AppShell->out($query); | |
$this->AppShell->out('User "' . $id . '" has a new primary key of: ' . $count); | |
$count++; | |
} | |
return true; | |
} | |
public function after($direction) { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment