进行迁移我收到此错误:
SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:alter table books
添加约束books_writer_id_foreign
外键(writer_id
)引用writers
({{1 }}))
我尝试了很多东西,但没有人看起来工作。
2018_02_18_3165165_create_books_table.php
id
2018_02_18_192915_create_writers_table
<?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');
}
}
修改:错误是因为第一次迁移是书籍,然后是造成错误的作者。
答案 0 :(得分:4)
有时根据我的经验,过于接近的时间戳会破坏代码并抛出异常,因为程序认为在books表尝试更改writers_table时间戳之后创建了writers表:
2018_02_16_31615
答案 1 :(得分:1)
更改迁移源your_table_name
Schema::create('your_table_name', function (Blueprint $table) {
$table->BigIncrements('id');
到
Schema::create('your_table_name', function (Blueprint $table) {
$table->increments('id');
答案 2 :(得分:0)
将其设为unsignedInteger
,因为您正在使用increments()
$table->unsignedInteger('writer_id')->nullable();
答案 3 :(得分:0)
将此行移至第一个闭包:
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup as soup
my_url = "https://www.transfermarkt.com/wettbewerbe/europa/"
client = Request(my_url, headers={"User-Agent" : "Mozilla/5.0"})
page = urlopen(client).read()
print(page)
在以下之后立即:
$table->integer('writer_id')->unsigned();
此外,您需要为两个迁移文件添加时间戳,以便Laravel首先创建$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
表,然后创建writers
表:
books