Cakephp:如何使用迁移来插入记录

时间:2015-06-08 15:13:18

标签: php sql cakephp cakephp-3.0

我正在使用CakePHP v3.x,我正试图弄清楚如何通过迁移工具插入一些记录。 The documentation仅列出修改架构的方法。我是否需要使用原始SQL手动插入记录?

1 个答案:

答案 0 :(得分:6)

CakePHP 3的Migration插件是一个Phinx包装器插件,因此可以使用up()方法添加记录: -

public function up() {
    // Save records to the newly created schema
}

public function down() {
    // Remove records
}

例如,您可以在TableRegistry上使用up添加新用户: -

public function up() {
    // Save records to the newly created schema
    $UsersTable = TableRegistry::get('Users');
    $user = $UsersTable->newEntity();

    $user->name = 'Joe Bloggs';
    $user->email = 'joe@example.com';

    $UsersTable->save($user);
}

如果使用TableRegistry,请不要忘记在迁移文件的顶部加入use Cake\ORM\TableRegistry;

对于CakeDC的Migration插件,您可以使用相关迁移文件中的callbacks插入记录: -

public function after($direction) {
    if ($direction === 'up') {
        // Save records to the newly created schema
    } elseif ($direction === 'down') {
        // Remove records
    }
}

注意:如果您使用的是Postgres驱动程序,则目前有一个bug需要一个小的解决方法才能使其正常工作。