常规错误:1215无法在Laravel中添加外键约束 [英] General error: 1215 Cannot add foreign key constraint in laravel
问题描述
进行迁移时出现此错误:
SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:更改表books
添加约束books_writer_id_foreign
外键(writer_id
)引用writers
(id
))
我尝试了很多事情,但没人能工作.
Doing the migrations I got this error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table books
add constraint books_writer_id_foreign
foreign key (writer_id
) references writers
(id
))
I've tried a lot of things but noone looks to work.
2018_02_18_3165165_create_books_table.php
2018_02_18_3165165_create_books_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name');
$table->text('description');
$table->integer('numPages');
$table->enum('language', ['spanish', 'english']);
$table->date('wrote_date')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
Schema::table('books', function (Blueprint $table) {
$table->integer('writer_id')->unsigned();
$table->foreign('writer_id')->references('id')->on('writers');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
2018_02_18_192915_create_writers_table
2018_02_18_192915_create_writers_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateWritersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('writers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('nationality');
$table->date('year_date')->nullable();
$table->date('dead_date')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('writers');
}
}
该错误是因为第一个迁移是书籍,然后是编写者导致该错误.
推荐答案
有时,根据我的经验,时间戳太短会破坏代码,并会引发异常,因为程序认为writers表是在books表尝试更改writers_table timestamp之后创建的像这样:
2018_02_16_31615
Sometimes based on my experience too close timestamps will break the code and will throw an exception because program thinks that writers table is created after books table try to change writers_table timestamp something like:
2018_02_16_31615
这篇关于常规错误:1215无法在Laravel中添加外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!