laravel-5 - SQLSTATE[HY000] : General error: 1215 Cannot add foreign key constraint Laravel

标签 laravel-5 foreign-keys migration

我正在尝试使用 artisan 创建外键,但出现此错误。

[Illuminate\Database\QueryException]                                                                                                                                                                             
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_comment_lot_id_foreign` foreign key (`comment_lot_id`) references `lots` (`lot_id`  
  ) on delete cascade) 

这是我的迁移:
<?php

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

class CreateCommentsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->text('comment');
            $table->integer('comment_lot_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('comments', function ($table) {
            $table->foreign('comment_lot_id')->references('lot_id')->on('lots')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropForeign(['comment_lot_id']);
        Schema::dropIfExists('comments');
    }
}

在我使用的批处理表中 lot_idid它模型 Lot.php 我添加:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Lot extends Model {
    protected $primaryKey = 'lot_id';

}

知道如何解决此错误吗?

最佳答案

报价 this answer:

To find the specific error run this:

SHOW ENGINE INNODB STATUS;

And look in the LATEST FOREIGN KEY ERROR section.


这可能是类型问题。 comment_lot_id必须与 lot_id 的类型完全相同.也许一个已签名,另一个未签名。

关于laravel-5 - SQLSTATE[HY000] : General error: 1215 Cannot add foreign key constraint Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43673142/

相关文章:

php - Laravel 容器和绑定(bind)

mysql - 外键必须是 mySQL 中的索引?

mysql - 如何从适用于 OpenVMS 的 Oracle RDB 迁移到 Windows 中的 MySQL?

laravel-5 - Laravel Excel - 选择要导出的列

Laravel - Composer 更新和托管 azure 问题

MYSQL外键errno : 150 cannot create tables

python - South 不会为现有应用程序生成或应用迁移,更改要迁移

c# - 迁移附加了 C# 应用程序的 Oracle 数据库 : How to manage database migration?

php - Laravel - 仅验证具有固定长度和所需空间的数字

mysql - mysql 外键约束错误