2016-02-13 64 views
1

我正尝试使用Laravel的迁移来创建外键。Laravel外键有什么问题?

Schema::create('articles', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('user_id')->unsinged(); 
     $table->string('title'); 
     $table->longText('body'); 
     $table->timestamp('published_at'); 
     $table->timestamps(); 

    }); 


    Schema::table('articles', function($table) { 
     $table->foreign('user_id') 
      ->references('id') 
      ->on('users') 
      ->onDelete('cascade'); 

    }); 

我收到以下错误,当我做php artisan migrate

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter ta ble laravel_articles add constraint articles_user_id_foreign foreign key (user_id ) references laravel_users (id) on delete cascade) `

+0

'unsinged();'?!? –

+0

@MarkBaker不起作用! – Ahmad

+0

这是相同的迁移吗? – Dencker

回答

4

你有方法的名称拼写错误。它应该是unsigned()unsinged()

Schema::create('articles', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('user_id')->unsigned(); 
    $table->string('title'); 
    $table->longText('body'); 
    $table->timestamp('published_at'); 
    $table->timestamps(); 
}); 

的架构Builder使用Fluent到链中的方法,即使链式方法unsinged不存在不抛出异常。尽管有错字,articles表仍然会被创建,但user_id列将是一个有符号的整数,并且由于users表中的id列是无符号整数,所以它将阻止创建约束。

+0

令人惊叹的感谢的人。 :-) – Ahmad