Laravel 4 Migration - 无法添加外键约束

时间:2013-09-25 02:44:36

标签: laravel laravel-4

这是我的迁移代码:

public function up()
{
    Schema::create('foos', function(Blueprint $table) {
        // Primary key
        $table->increments('id');

        // Standard
        $table->engine = 'InnoDB';
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('bars', function(Blueprint $table) {
        // Primary key
        $table->increments('id');

        // Define foreign key
        $table->integer('foo_id')->unsigned;

        // Foreign key contraints
        // NOTE: causes "General error: 1215 Cannot add foreign key constraint"
        // $table->foreign('foo_id')->references('id')->on('foos');

        // Standard
        $table->engine = 'InnoDB';
        $table->timestamps();
        $table->softDeletes();
    });
}

public function down()
{
    Schema::drop('foos');
    Schema::drop('bars');
}

当没有注释掉定义外键约束的代码时,我在命令行上收到以下错误:常规错误:1215无法添加外键约束

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:15)

$table->integer('foo_id')->unsigned;

应该是

$table->integer('foo_id')->unsigned();

或者您可以使用简短版本:

$table->unsignedInteger('foo_id');