简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM