【发布时间】:2015-06-08 15:13:17
【问题描述】:
我正在使用 CakePHP v3.x,我正在尝试弄清楚如何通过迁移工具插入一些记录。 The documentation 只列出了修改模式的方法。我需要使用原始 SQL 手动插入记录吗?
【问题讨论】:
标签: php sql cakephp cakephp-3.0
我正在使用 CakePHP v3.x,我正在尝试弄清楚如何通过迁移工具插入一些记录。 The documentation 只列出了修改模式的方法。我需要使用原始 SQL 手动插入记录吗?
【问题讨论】:
标签: php sql cakephp cakephp-3.0
CakePHP 3 的 Migration 插件是一个 Phinx 包装器插件,因此可以使用 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,需要一个小的解决方法才能使其正常工作。
【讨论】:
insert()方法,然而现在是not documented github.com/robmorgan/phinx/pull/457