【发布时间】:2017-04-28 06:10:05
【问题描述】:
我尝试使用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_id 作为 id 它模型 Lot.php 我添加:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lot extends Model {
protected $primaryKey = 'lot_id';
}
知道如何解决此错误吗?
【问题讨论】:
-
如下所述,确保两个整数完全相同,无符号,长度等。这通常是失败的原因。
-
要查找特定错误,请在数据库电机上运行
SHOW ENGINE INNODB STATUS;。学分stackoverflow.com/questions/15534977/…
标签: laravel-5 foreign-keys migration