【问题标题】:Laravel 5 migration - foreign key constraint failsLaravel 5 迁移 - 外键约束失败
【发布时间】:2016-01-20 06:20:34
【问题描述】:

我在运行迁移时遇到问题。我有一个带有一些表的 mysql 数据库。具体表为product_blender。表中有些字段是这样的:

  • id (PK)
  • area_id (FK)
  • 居民(varchar)
  • heater_type_id (FK)
  • ...

现在我想创建另一个名为installateur_types 的表。该表需要包含一个 PK 和一个 varchar 字段。我还想在 product_blender 表中创建一个 FK 到我新创建的表的 id

这就是我所做的:

已创建迁移以创建表:

public function up()
{
    Schema::create('installateur_types', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('type');
    });
}

public function down()
{
    Schema::drop('installateur_types');
}

运行迁移,这是成功的。使用正确的字段创建表。

然后我创建了迁移以将 FK 字段添加到 product_blender 表中

public function up()
{
    Schema::table('product_blenders', function ($table) {
        $table->integer('installateurtype_id')->unsigned();
        $table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade');
    });
}

public function down()
{
    //
}

当我现在运行迁移时,我收到以下错误:

我做错了什么?

【问题讨论】:

  • product_blenders 表以前是否存在?

标签: mysql database laravel laravel-5 foreign-keys


【解决方案1】:

如果您的products_blender 表不为空,那么当您添加一个不为空的新列(这是 eloquent 的默认值)时,它将自行假设一些默认值。此新列所引用的表中可能没有该值,从而导致外键约束失败。

解决此问题的一种方法是为新列提供默认值或将其设为可为空

$table->integer('installateurtype_id')->unsigned()->nullable();
$table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade');

还有另一种解决方案,可以关闭此检查,可以使用DB::statement('SET FOREIGN_KEY_CHECKS=0;') 完成。然后再次使用DB::statement('SET FOREIGN_KEY_CHECKS=1;') 将其转为未来。在您的代码中,您可以执行类似的操作

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$table->integer('installateurtype_id')->unsigned();
$table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade');
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2020-05-20
    • 2019-05-23
    相关资源
    最近更新 更多