簡體   English   中英

1215無法在laravel 5中添加外鍵約束,外鍵

[英]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 )引用contactsid )刪除級聯更新級聯)

您應該確保所有列都是相同的類型。 例如,在表contactsid列是無符號大整數,因此當您在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM