Archived
1
0
Fork 0

migration: 20180814172405_user_split_name.php

This commit is contained in:
Henrik Hautakoski 2018-08-14 20:21:20 +02:00
parent db478d671c
commit a9081dcfc8
No known key found for this signature in database
GPG key ID: 839F3A7EAFAEAFAA

View 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();
}
}