2

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();
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Amrinder Singh
  • 5,300
  • 12
  • 46
  • 88

2 Answers2

7

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.

code-kobold
  • 829
  • 14
  • 18
2

In Phinx, you can use the below code to add foreign key with cascading

$table->addForeignKey('user_id', 'users', 'id', ['delete'=> 'CASCADE', 'update'=> 'CASCADE']);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93