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



我正在尝试创建一个表格并将其链接到AD(属性ID(。我遇到了这个错误

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

这些是我的迁移文件

2018_02_14_191609_create_property_adverts_table

<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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 IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
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');
    }
}

所以

使其成为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');
    });
}

最新更新