Skip to content

Instantly share code, notes, and snippets.

@sime
Created April 19, 2013 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sime/5419482 to your computer and use it in GitHub Desktop.
Save sime/5419482 to your computer and use it in GitHub Desktop.
Migrating from string to integer primary keys in CakePHP
<?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