Skip to content

Instantly share code, notes, and snippets.

@sime sime/migration.php
Created Apr 19, 2013

Embed
What would you like to do?
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
You can’t perform that action at this time.