Search code examples
mysqlcakephpdatabase-migrationphinx

How to set Foreign Key Constraint in Cakephp 3.3 Migration?


I am new to Cakephp and building an application with Cakephp3.3, I am working on Migrations, I have to create a user_infos table, and want to add a new column user_id, I am able to add new columns through migrations but I don't know how to add foreign key.

here is my migration file

    public function change()
    {
        $table = $this->table('user_infos');
        $table->addColumn('user_id', 'integer', [
            'default' => null,
            'limit' => 11,
            'null' => false,
        ]);
        $table->addColumn('title', 'string', [
            'default' => null,
            'limit' => 255,
            'null' => false,
        ]);
        $table->addColumn('created', 'datetime', [
            'default' => null,
            'null' => false,
        ]);
        $table->addColumn('modified', 'datetime', [
            'default' => null,
            'null' => false,
        ]);
        $table->create();
    }

Solution

  • Your migration seems to be based on Phinx; you can find relevant methods in Phinx\Db\Table. Add

    ->addIndex(['user_id'])
    ->addForeignKey('user_id', 'users', 'id')
    

    to your migration for the constraint on the users table.