为什么codeigniter 4给出错误“无法添加外键约束”

fykwrbwg  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(137)

我正在学习Codeigniter 4,我正在使用迁移来创建表。以下是我的迁移代码:

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateDivisionTable extends Migration
{
    public function up()
    {
        $this->forge->addField([

            'id' => [

                'type' => 'INT',
                'constraint' => 7,
                'unsigned' => true,
                'auto_increment' => true
            ],

            'name' => [

                'type' => 'VARCHAR',
                'constraint' => '128'

            ],

            'entity_id' => [
                'type' => 'INT',
                'contraint' => '7'
            ]

        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->addForeignKey('entity_id', 'entities', 'id');
        $this->forge->createTable('divisions');
        //
    }

    public function down()
    {
        $this->forge->dropTable('divisions');
    }
}

但这给予我的错误像:

Cannot add foreign key constraint

at SYSTEMPATH/Database/BaseConnection.php:646

Backtrace:
  1    SYSTEMPATH/Database/Forge.php:546
       CodeIgniter\Database\BaseConnection()->query('CREATE TABLE `divisions` (
        `id` INT(7) UNSIGNED NOT NULL AUTO_INCREMENT,
        `name` VARCHAR(128) NOT NULL,
        `entity_id` INT NOT NULL,
        CONSTRAINT `pk_divisions` PRIMARY KEY(`id`),
        CONSTRAINT `divisions_entity_id_foreign` FOREIGN KEY (`entity_id`) REFERENCES `entities`(`id`)
) DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci')

我的实体表具有带主键的ID。我该如何解决这个问题?如果我注解掉addForeignKey(),它对我有用。但我需要设置外键。

7y4bm7vi

7y4bm7vi1#

请尝试颠倒顺序,首先运行实体迁移,然后运行部门迁移,因为您需要现有的关系字段

相关问题