Laravel 4迁移问题中的外键问题

Jas*_*nNZ 25 mysql laravel laravel-4

我刚刚创建了一个新的Laravel 4项目,并且发现模式构建器的外键方面发生了奇怪的事情.如果我->foreign()在任何迁移中使用该方法,我会抛出MySQL错误150和一般错误1005.根据laravel.com/docs的文档,底部的两个场景应该有效吗?谁知道他们为什么不这样做?

以下工作:

    Schema::create('areas', function($table)
    {
        $table->engine ='InnoDB';
        $table->increments('id');

        $table->integer('region_id')->references('id')->on('regions');

        $table->string('name', 160);
        $table->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

但这两个不起作用:

    Schema::create('areas', function($table)
    {
        $table->engine ='InnoDB';
        $table->increments('id');

        $table->foreign('region_id')->references('id')->on('regions');

        $table->string('name', 160);
        $table->timestamps();
    });

    Schema::create('areas', function($table)
    {
        $table->engine ='InnoDB';
        $table->increments('id');

        $table->integer('region_id');
        $table->foreign('region_id')->references('id')->on('regions');

        $table->string('name', 160);
        $table->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

net*_*n73 53

检查你的id类型.Laravel 4使用int(10)unsigned创建一个增量id.如果您创建一个基本整数并尝试在其上放置一个外键,它将失败.

如此链接的文档中所建议的那样,您应该创建外部ID $table->unsignedInteger(YOUR_ID_NAME);以使其工作.

  • 例如:(users table)`$ table-> incrementments('id');`和(posts table)`$ table-> unsignedInteger('user_id');`\n` $ table-> foreign('user_id') ) - >的引用( 'ID') - >上( '用户');` (5认同)

Tim*_*lvy 7

还有一些答案在这个问题"一般错误:1005无法创建表"使用Laravel架构构建和外键

列出的答案摘要,包括我的:

  1. 外键通常需要InnoDb,因此设置默认引擎,或明确指定 $table->engine = 'InnoDB'; 如果您的表已经创建并默认为MyISAM,您可能需要更改它.

  2. 外键需要引用的表存在.在创建密钥之前,请确保在先前的迁移中创建了引用的表.考虑在单独的迁移中创建密钥以确保.

  3. 外键要求数据类型一致.检查引用的字段是否是相同的类型,无论是有符号还是无符号,它的长度是否相同(或更小).

  4. 如果要在手动编码迁移和使用生成器之间切换,请确保检查正在使用的ID类型.Artisan 默认使用incrementments(),但Jeffrey Way似乎更喜欢整数('id',true).


小智 5

前一天有同样的问题.

问题的根源是:具有外键的列必须与该键的类型相同.你有不同的类型:INT/UNSIGNED INT

这使得id成为了一个 UNSIGNED INT

$table->increments('id');
Run Code Online (Sandbox Code Playgroud)

这使得region_id成为了一个 INT

$table->integer('region_id')->references('id')->on('regions'); 
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,使REGION_ID的UNSIGNED INT

$table->integer('region_id')->unsigned()->references('id')->on('regions'); 
                              ^^^^^^^^^ note here
Run Code Online (Sandbox Code Playgroud)

Laravel的文档提到了这一点:

注意:创建引用递增整数的外键时,请记住始终使外键列无符号.