m4r*_*ii0 3 php mysql migration laravel
做迁移我得到这个错误: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table booksadd constraint books_writer_id_foreignforeign key ( writer_id) references 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');
}
}
Run Code Online (Sandbox Code Playgroud)
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');
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:错误是因为第一次迁移是书籍,然后是导致错误的作者。
有时根据我的经验,太接近的时间戳会破坏代码并抛出异常,因为程序认为在书籍表尝试更改 writers_table 时间戳之后创建了 writers 表,例如:
2018_02_16_31615
unsignedInteger因为你正在使用它increments()
$table->unsignedInteger('writer_id')->nullable();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9948 次 |
| 最近记录: |