![](/img/trans.png)
[英]General Error 1215: Cannot Add Foreign Key Constraint for Laravel 5
[英]1215 General error: Cannot add foreign key constraint Laravel
我有一個已創建外鍵約束的表:
錯誤:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
constraint (SQL: alter table `league_seasons` add
constraint `league_seasons_league_id_foreign` foreign key (`league_id`)
references `leagues` (`id`) on delete cascade)
這是排行榜
public function up() {
Schema::create('leagues', function (Blueprint $table) {
$table->integer('id');
$table->increments('increment_id');
$table->string('type')->nullable();
$table->integer('legacy_id')->nullable();
$table->integer('country_id')->nullable();
}
這是 League_seasons 表
public function up() {
Schema::create('league_seasons', function (Blueprint $table) {
$table->integer('id');
$table->increments('increment_id');
$table->string('name')->nullable();
$table->unsignedInteger('league_id');
$table->string('is_current_season')->nullable();
$table->string('current_round_id')->nullable();
$table->string('current_stage_id')->nullable();
App\Helpers\DbExtender::defaultParams($table, true);
});
Schema::table('league_seasons', function (Blueprint $table) {
$table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade');
});
}
我試過交換 unSignedInteger、BigInteger 但它們似乎都沒有工作。 知道為什么會這樣嗎? 謝謝
正如@repat 指出的那樣,在兩個表上添加 unSignedInteger 和 index() 對我有用。
最終聯賽表:
public function up() {
Schema::create('leagues', function (Blueprint $table) {
$table->unsignedInteger('id')->index();
$table->increments('increment_id');
$table->string('type')->nullable();
$table->integer('legacy_id')->nullable();
$table->integer('country_id')->nullable();
$table->string('name')->nullable();
}
最終的 League_seasons 表:
public function up() {
Schema::create('league_seasons', function (Blueprint $table) {
$table->integer('id');
$table->increments('increment_id');
$table->string('name')->nullable();
$table->unsignedInteger('league_id')->index();
$table->string('is_current_season')->nullable();
$table->string('current_round_id')->nullable();
$table->string('current_stage_id')->nullable();
App\Helpers\DbExtender::defaultParams($table, true);
});
Schema::table('league_seasons', function (Blueprint $table) {
$table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade');
});
}
要創建Foreign key
, child column
的數據類型必須與parent column
完全匹配。 例如,因為leagues.id
是一個integer
, league_seasons.league_id
也需要是一個integer
,而不是一個unsignedInteger
integer
。
所以改變
$table->unsignedInteger('league_id');
到
$table->integer('league_id');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.