基本上,我试图将我的迁移上传到数据库中,但是我遇到了一些问题,因为我试图引用尚未创建的表中的列。我考虑过将它们1迁移1,但是例如我有组和用户表。该组有一个创建者(用户),而该用户有一个组。所以我不能同时引用它们,因为它们不是创建的。
这是我的错误:
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');
});
}
答案 0 :(得分:1)
正确的方法是创建用于创建/删除具有较低时间戳的表的迁移(因此首先执行),
然后只需使用时间戳大于以前使用的迁移来添加/删除所有外键。这样,您就不会像现在那样遇到问题。
添加外键的迁移示例:
class AddForeignKeysToMyTableTable extends Migration {
public function up()
{
Schema::table('my_table', function(Blueprint $table)
{
$table->foreign('my_field_id', ...
您可能还想尝试使用一些生成器来为您创建所有迁移。这一步骤将确保您所有的制表迁移均在添加外键之前进行: