davidjh
davidjh

Reputation: 417

Cakephp migrations - General error: 1215 Cannot add foreign key constraint

I am having issues creating a foreign key in some migrations.

I have the following:

20180926184217_Courses.php

public function change()
{
    $table = $this->table('courses', ['id' => true, 'primary_key' => ['id']]);
    $table
        ->addColumn('name', 'string', ['default' => null, 'limit' => 150, 'null' => false])
        ->addColumn('town', 'string', ['default' => null, 'limit' => 50, 'null' => true])
        ->create();
}

20180926191546_Scorecards.php

public function change()
{
    $table = $this->table('scorecards', ['id' => true, 'primary_key' => ['id']]);
    $table
        ->addColumn('course_id', 'integer', ['default' => null, 'limit' => 10, 'null' => false])
        ->addColumn('description', 'string', ['default' => null, 'limit' => 255, 'null' => true])
        ->addColumn('tee', 'string', ['default' => null, 'limit' => 15, 'null' => false])
        ->addForeignKey('course_id', 'courses', 'id', ['delete' => 'SET_NULL', 'update' => 'NO_ACTION', 'constraint' => 'fk_scorecard_course'])
        ->create();
}

When I run bin/cake migrations migrate I get the following error:

Exception: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint in [*/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php, line 167] 2018-09-26 19:12:50 Error: [PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint in */vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php on line 167

Can anyone help please? I have looked at other answers on here and none seemed to help.

Dave

Upvotes: 0

Views: 914

Answers (1)

Sergio Daniel Torres
Sergio Daniel Torres

Reputation: 11

You can't SET_NULL on delete action when your column is not nullable. Change the code and you will be ready for your migration.

Upvotes: 1

Related Questions