进行迁移时我收到此错误:
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter tablebooks
添加约束books_writer_id_foreign
外键(writer_id
) 参考writers
(id
))
我尝试了很多事情,但没有人看起来能起作用。
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_表
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');
}
}
Edit: 该错误是因为第一次迁移是书籍,然后是作者导致了该错误。
有时根据我的经验,太接近的时间戳会破坏代码并引发异常,因为程序认为 writers 表是在 books 表尝试更改 writers_table 时间戳后创建的,例如:
2018_02_16_31615
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)