Cakephp: How to use migration to insert records

喜你入骨 提交于 2019-12-01 07:36:37

问题


I'm using CakePHP v3.x and I'm trying to figure out how to insert some records via the migrations tool. The documentation only lists methods for modifying the schema. Will I need to insert records manually with raw SQL?


回答1:


CakePHP 3's Migration plugin is a Phinx wrapper plugin, so adding records can be done using the up() method:-

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

public function down() {
    // Remove records
}

For example, you could add a new user using TableRegistry on 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);
}

If using TableRegistry don't forget to include use Cake\ORM\TableRegistry; at the top of the migration file.

For CakeDC's Migration plugin you can insert records using the callbacks in the relevant migration file:-

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

NOTE: If you are using the Postgres driver, there is currently a bug which requires a small workaround to make this work.



来源:https://stackoverflow.com/questions/30712896/cakephp-how-to-use-migration-to-insert-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!