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

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

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

  1. <?php
  2. namespace App\Database\Migrations;
  3. use CodeIgniter\Database\Migration;
  4. class CreateDivisionTable extends Migration
  5. {
  6. public function up()
  7. {
  8. $this->forge->addField([
  9. 'id' => [
  10. 'type' => 'INT',
  11. 'constraint' => 7,
  12. 'unsigned' => true,
  13. 'auto_increment' => true
  14. ],
  15. 'name' => [
  16. 'type' => 'VARCHAR',
  17. 'constraint' => '128'
  18. ],
  19. 'entity_id' => [
  20. 'type' => 'INT',
  21. 'contraint' => '7'
  22. ]
  23. ]);
  24. $this->forge->addPrimaryKey('id');
  25. $this->forge->addForeignKey('entity_id', 'entities', 'id');
  26. $this->forge->createTable('divisions');
  27. //
  28. }
  29. public function down()
  30. {
  31. $this->forge->dropTable('divisions');
  32. }
  33. }

但这给予我的错误像:

  1. Cannot add foreign key constraint
  2. at SYSTEMPATH/Database/BaseConnection.php:646
  3. Backtrace:
  4. 1 SYSTEMPATH/Database/Forge.php:546
  5. CodeIgniter\Database\BaseConnection()->query('CREATE TABLE `divisions` (
  6. `id` INT(7) UNSIGNED NOT NULL AUTO_INCREMENT,
  7. `name` VARCHAR(128) NOT NULL,
  8. `entity_id` INT NOT NULL,
  9. CONSTRAINT `pk_divisions` PRIMARY KEY(`id`),
  10. CONSTRAINT `divisions_entity_id_foreign` FOREIGN KEY (`entity_id`) REFERENCES `entities`(`id`)
  11. ) DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci')

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

7y4bm7vi

7y4bm7vi1#

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

相关问题