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

eme*_*his 2 php sql cakephp cakephp-3.0

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

drm*_*nja 5

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

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

public function down() {
    // Remove records
}
Run Code Online (Sandbox Code Playgroud)

例如,您可以使用TableRegistryon 添加新用户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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

注意:如果您使用的是Postgres驱动程序,则目前存在一个错误,需要一个小的解决方法才能使其工作.

  • 看起来像前一段时间,添加了`insert()`方法,但它是[**未记录**](https://github.com/robmorgan/phinx/pull/639)但**https:// github.com/robmorgan/phinx/pull/457** (2认同)