1215无法在laravel 5中添加外键约束,外键

时间:2019-04-23 18:55:39

标签: sql laravel laravel-5 migration database-migration

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迁移:新鲜并获取 SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:更改表contacts_relations添加约束contacts_relations_contact_id_foreign外键(contact_id)引用contactsid)在更新级联上删除级联)

1 个答案:

答案 0 :(得分:0)

您应确保所有列的类型均相同。例如,在表contacts中,id列是无符号的大整数,因此,当您在contact_id中创建contacts_relations列而不是:

$table->unsignedInteger('phone_id')->nullable()->default(1);

应该是:

$table->unsignedBigInteger('phone_id')->nullable()->default(1);

contacts_relations_id列相似的事物