[英]1215 Cannot add foreign key constraint in laravel 5, foreign key
2019_04_23_164151_create_contacts_table.php遷移文件
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContactsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('surname');
$table->timestamps();
});
Schema::create('contacts_relations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('phone_id')->nullable()->default(1);
$table->unsignedInteger('contact_id')->nullable()->default(1);
});
Schema::create('contact_phone', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('phone_number');
$table->unsignedInteger('contacts_relations_id')->nullable()->default(1);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contacts');
}}
2019_04_24_183110_contacts_relations.php外鍵設置器
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ContactsRelations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('contacts_relations', function (Blueprint $table) {
$table->foreign('contact_id')->references('id')->on('contacts');
});
Schema::table('contact_phone', function (Blueprint $table) {
$table->foreign('contacts_relations_id')->references('id')->on('contacts_relations');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
運行php artisan migrate:fresh並獲取SQLSTATE [HY000]:常規錯誤:1215無法添加外鍵約束(SQL:alter table contacts_relations
添加約束contacts_relations_contact_id_foreign
外鍵( contact_id
)引用contacts
( id
)刪除級聯更新級聯)
您應該確保所有列都是相同的類型。 例如,在表contacts
, id
列是無符號大整數,因此當您在contacts_relations
創建contact_id
列而不是:
$table->unsignedInteger('phone_id')->nullable()->default(1);
它應該是:
$table->unsignedBigInteger('phone_id')->nullable()->default(1);
對於contacts_relations_id
列也類似
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.