基本上,我正在尝试将迁移上载到数据库,但是我遇到了一些问题,因为我正在尝试引用尚未创建的表中的列。我考虑过一个接一个地迁移它们,但例如,我有组表和用户表。组有一个创建者(用户),用户有一个组。所以我不能同时引用它们,因为它们不是被创建的。
这是我的错误:
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `vote-system`.`#sql-1a08_37` (errno: 150 "Foreign key constraint is incorrectly formed")")
组迁移
public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('created_by')->unsigned();
$table->timestamps();
// Relationships
$table->foreign('created_by')->references('id')->on('users');
});
}
用户迁移
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->ipAddress('ip');
$table->integer('votes_left');
$table->rememberToken();
$table->timestamps();
$table->integer('group_id')->unsigned();
// Relationships
$table->foreign('group_id')->references('id')->on('groups');
});
}
1条答案
按热度按时间uurv41yg1#
正确的方法是创建迁移,以便创建/删除时间戳较低的表(因此首先执行这些表),
然后只需添加/删除时间戳大于以前使用的迁移的所有外键。这样你就不会像现在这样惹麻烦了。
添加外键的迁移示例:
您可能还想尝试一些生成器来为您创建所有迁移。这将确保所有表生成迁移在添加外键之前运行:
https://github.com/xethron/migrations-generator