Laravel迁移的外键导致一般错误1215

时间:2015-02-10 01:25:59

标签: laravel artisan artisan-migrate

我正在尝试使用Laravels迁移创建具有外键的多个表。我有一个问题迁移表,如此

Schema::create('problems', function($table)
        {
            $table->increments('id');
            $table->integer('created_by')->unsigned();
            $table->foreign('created_by')->references('id')->on('users');
            $table->integer('category')->unsigned();
            $table->foreign('category')->references('id')->on('categories');
            $table->timestamps();
        });

类别迁移

Schema::create('categories', function($table)
        {
            $table->increments('id');
            $table->string('category_name');
            $table->timestamps();
        });

我的第一个进入用户迁移的外键工作正常,但只要它击中类别ID的外键,它就会给出一个

  

SQLSTATE HY000一般错误1215 Impossible d'ajouter des contraintes   d'index externe(SQL; alter table' problems'添加约束   problems_category_foreign外键('category')引用   'categories'('id'))

(我无法正确阅读法语,我不知道为什么它会给我带来法语错误。我无法找到改变它的方法,因为我不是法语,我也无法理解)

我不明白为什么这对于一个而不是另一个当它们基本上是相同的东西时会起作用。

4 个答案:

答案 0 :(得分:3)

您需要确保迁移文件的顺序正常。例如,在实际创建类别表本身之前,无法使用在类别表上引用id的外键创建问题表。

对于法语错误问题,请查看此question

答案 1 :(得分:1)

您必须更改迁移顺序

|-database/
|--migrations/
|---2015_02_02_141725_create_problems_table.php
|---2015_03_01_234626_create_categories_table.php

应该是:

|-database/
|--migrations/
|---2015_01_01_234626_create_categories_table.php
|---2015_02_02_141725_create_problems_table.php

最后:

php artisan migrate

答案 2 :(得分:0)

我必须在不同的迁移文件中添加外键,修复问题。

答案 3 :(得分:0)

我几天前遇到了同样的问题,问题如下:

在使用$table->increments('id');时,会生成unsigned整数,其中长度为10 。并且$table->integer('user_id')生成一个非unsigned整数长度为11

要解决此问题,您可能会放弃unsigned并将所有与其他字段相关的字段设置为auto increment字段,如下所示:

$table->integer('id', true); // true represents the auto increment type

当然,设置$table->engine = 'InnoDB';

相关问题