【问题标题】:SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint - LaravelSQLSTATE [HY000]:一般错误:1215 无法添加外键约束 - Laravel
【发布时间】:2018-07-29 00:15:42
【问题描述】:

我正在尝试创建一个表格来保存照片并将其链接到广告(属性 ID)。 我收到此错误

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束

这些是我的迁移文件

2018_02_14_191609_create_property_adverts_table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePropertyAdvertsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('property_adverts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('address');
            $table->string('county');
            $table->string('town');
            $table->string('type');
            $table->string('rent');
            $table->string('date');
            $table->string('bedrooms');
            $table->string('bathrooms');
            $table->string('furnished');
            $table->longText('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('property_adverts');
    }
}

2018_02_18_165845_create_property_advert_photos_table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePropertyAdvertPhotosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('property_advert_photos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('propertyadvert_id')->nullable();
            $table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('property_advert_photos');
    }
}

所以

【问题讨论】:

  • 尝试删除propertyadvert_id列的nullable()方法,改成unsigned()

标签: laravel


【解决方案1】:

设为unsigned,因为您使用的是increments()。并将 FK 约束部分移动到单独的闭包中:

public function up()
{
    Schema::create('property_advert_photos', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('propertyadvert_id')->nullable();
        $table->timestamps();
    });

    Schema::table('property_advert_photos', function (Blueprint $table) {
        $table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
    });
}

【讨论】:

  • 太棒了。你是传奇
  • @AmieAngle 很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 2019-08-02
  • 2021-07-03
  • 2020-01-14
  • 2022-11-18
  • 2016-12-20
  • 2019-11-11
  • 2019-07-27
  • 2021-03-31
相关资源
最近更新 更多