我正在学习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(),它对我有用。但我需要设置外键。
1条答案
按热度按时间7y4bm7vi1#
请尝试颠倒顺序,首先运行实体迁移,然后运行部门迁移,因为您需要现有的关系字段