Search code examples
phpsqlcakephpcakephp-3.0

Cakephp: How to use migration to insert records


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?


Solution

  • 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 = '[email protected]';
    
        $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.