我正在尝试使用 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';
}
知道如何解决此错误吗?
最佳答案
报价 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/