Search code examples
phpcakephpphinx

How to access the auto-generated ID from a Phinx migration insert?


PHP Phinx is a Database Seeder / Migration library from CakePHP.

This will create a fake user, but how would I create a row that has a FOREIGN KEY (or regular ID reference) to the id of that new user, i.e. a sub-user?

<?php

use Phinx\Seed\AbstractSeed;

class UserSeeder extends AbstractSeed
{
    public function run()
    {
        $faker = Faker\Factory::create();
        $data = [];
        for ($i = 0; $i < 100; $i++) {
            $data[] = [
                'username'      => $faker->userName,
                'password'      => sha1($faker->password),
                'password_salt' => sha1('foo'),
                'email'         => $faker->email,
                'first_name'    => $faker->firstName,
                'last_name'     => $faker->lastName,
                'created'       => date('Y-m-d H:i:s'),
            ];
        }

        $this->insert('users', $data);
    }
}

Solution

  • This should return the equivalent of SELECT LAST_INSERT_ID():

    $this->getAdapter()->getConnection()->lastInsertId();
    

    Reference: https://github.com/cakephp/phinx/issues/819