Laravel 4 Migration无法添加外键

时间:2018-06-06 05:38:24

标签: mysql database laravel migration

我正在尝试将一个新表添加到laravel 4x项目中,该项目的外键引用返回到已有数据的现有表中的主键。

这是我添加新表的迁移文件

<?php

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

class CreateCustomResponsesTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('custom_responses', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('hotel_id')->unsigned();
        $table->dateTime('created')->nullable();
        $table->dateTime('last_changed')->nullable();
        $table->string('response_type')->nullable();
        $table->mediumText('custom_response')->nullable();
    });

    Schema::table('custom_responses', function($table) {
        $table->foreign('hotel_id')->references('id')->on('properties');
    });

}

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

但是我也尝试过像这样的迁移文件

<?php

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

class CreateCustomResponsesTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('custom_responses', function (Blueprint $table) {
        $table->increments('id');
        $table->dateTime('created')->nullable();
        $table->dateTime('last_changed')->nullable();
        $table->string('response_type')->nullable();
        $table->mediumText('custom_response')->nullable();
        $table->integer('hotel_id')->unsigned();            
        $table->foreign('hotel_id')->references('id')->on('properties');
    });

}

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

当我查看现有的属性表时,我看到了

enter image description here

但是当我尝试运行迁移时,我得到了

[Illuminate\Database\QueryException]                                                                                                                                                                                   
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `custom_responses` add constraint custom_responses_hotel_id_foreign foreign key (`hotel_id`) references `properties` (`id`))  

[PDOException]                                                          
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

从扫描SO上的类似问题,以及谷歌搜索错误的典型原因是数据类型不匹配,或者当只有InnoDB支持外键时新表是MyISAM。从我可以看到的所有内容都创建了新表InnoDB并且数据类型匹配。

任何人都可以指出我缺少的东西吗?

0 个答案:

没有答案