【问题标题】:1215 Cannot add foreign key constraint in laravel 5, foreign key1215 不能在laravel 5中添加外键约束,外键
【发布时间】:2019-04-23 18:55:39
【问题描述】:

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 and get SQLSTATE [HY000]: 一般错误: 1215 无法添加外键约束 (SQL: alter table contacts_relations add constraintcontacts_relations_contact_id_foreign foreign key (contact_id) referencescontacts (id) on delete cascade on更新级联)

【问题讨论】:

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


    【解决方案1】:

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

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

    应该是:

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

    contacts_relations_id 列的类似情况

    【讨论】:

    • 也因为有一个默认值 remove nullable $table->unsignedBigInteger('phone_id')->default(1);
    • @Rachid 好吧,默认值可能是 1,但在某些情况下,您可能希望设置为 null
    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 2015-01-24
    • 2019-09-08
    • 2020-09-21
    • 2019-07-31
    相关资源
    最近更新 更多