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

Cakephp: How to use migration to insert records

我正在使用 CakePHP v3.x,我正在尝试了解如何通过迁移工具插入一些记录。 The documentation 仅列出修改模式的方法。我需要使用原始 SQL 手动插入记录吗?

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

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

public function down() {
    // Remove records
}

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

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 的迁移插件,您可以在相关迁移文件中使用 callbacks 插入记录:-

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

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