尝试迁移时出现此错误:
SQLSTATE[HY000]: General error: 1005 Can't create table testing.#sql-1848_3ae (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table gallery add constraint gallery_user_id_foreign foreign key (user_id) references users (id))
[PDOException] SQLSTATE [HY000]:常规错误:1005无法创建表测试。#sql-1848_3ae(错误:150“外键约束形成错误”)
这是我的迁移:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
class CreateGalleryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('gallery', function (Blueprint $table) {
$table->increments('id');
$table->string('description')->nullable();
$table->integer('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('gallery');
}
}
答案 0 :(得分:1)
我不相信你可以在Schema :: create()中设置一个forgein键;
在你的up方法中添加它,但在Schema :: create();
之外Schema::table('gallery', function ($table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
}
另外,请考虑在down()函数中添加以下内容。由于外键约束,我遇到了尝试重置迁移而无法正常工作的问题。
$table->dropForeign('gallery_user_id_foreign');