SQLSTATE [HY000]:常规错误:1215无法添加外键约束 - Laravel

时间:2018-02-18 17:41:36

标签: laravel

我尝试创建一个表来保存照片并将其链接到广告(属性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');
    }
}

所以

1 个答案:

答案 0 :(得分: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');
    });
}