migration: 20180814172405_user_split_name.php
This commit is contained in:
parent
db478d671c
commit
a9081dcfc8
1 changed files with 45 additions and 0 deletions
45
app/migrations/20180814172405_user_split_name.php
Normal file
45
app/migrations/20180814172405_user_split_name.php
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
|
||||
use Phinx\Migration\AbstractMigration;
|
||||
|
||||
class UserSplitName extends AbstractMigration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$this->getAdapter()->beginTransaction();
|
||||
|
||||
// Rename "name" to "firstname" and add "lastname".
|
||||
$this->table('user')
|
||||
->renameColumn('name', 'firstname')
|
||||
->addColumn('lastname','string', [
|
||||
'length' => 128,
|
||||
'after' => 'firstname',
|
||||
'null' => true
|
||||
])
|
||||
->save();
|
||||
|
||||
// Update row data, moving everything after first space to from lastname.
|
||||
foreach($this->fetchAll("SELECT `id`,`firstname` FROM `user`") as $row) {
|
||||
|
||||
$builder = $this->getQueryBuilder()->update('user')
|
||||
->where(['id' => $row['id']]);
|
||||
|
||||
$firstname = $row['firstname'];
|
||||
|
||||
// If we find a space.
|
||||
$pos = strpos($firstname, ' ');
|
||||
if ($pos !== false) {
|
||||
// Set everything after the first space to lastname.
|
||||
$builder->set('lastname', substr($firstname, $pos+1));
|
||||
|
||||
// Remove everything after first space from firstname.
|
||||
$firstname = substr($firstname, 0, $pos);
|
||||
}
|
||||
|
||||
$builder->set('firstname', $firstname);
|
||||
$builder->execute();
|
||||
}
|
||||
$this->getAdapter()->commitTransaction();
|
||||
}
|
||||
}
|
||||
Reference in a new issue