2

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);
    }
}
miken32
  • 42,008
  • 16
  • 111
  • 154
Jonathan
  • 6,741
  • 7
  • 52
  • 69

1 Answers1

9

This should return the equivalent of SELECT LAST_INSERT_ID():

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

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

miken32
  • 42,008
  • 16
  • 111
  • 154
  • Exactly what what I needed, thanks. I'd be curious how it behaves with multiple `insert`s before a `save`? Also does it have to be called after `save()`? – Jonathan Nov 21 '18 at 02:52
  • That value would be updated with every `INSERT` operation on the database table, so if you do multiple inserts in a single transaction you'd only see the last one. Note that this isn't table specific either, it will return the last ID from any table that had the most recent insert. – miken32 Nov 21 '18 at 02:54
  • I'm not familiar with Phinx, so not sure if inserts are queued up and executed with `save()` or what. – miken32 Nov 21 '18 at 02:56