1

我知道这已经被回答了很多次,因为我在写这个问题时看到了很多答案建议,但没有一个真正让我得到正确的答案。

当我尝试向表中添加新字段并在 laravel 中使用 artisan migrate 时出现错误

General error: 1215 Cannot add foreign key constraint (SQL: alter table `pages` add constraint pages_page_status_foreign foreign key (`page_status`) references `page_status` (`status_value`))

但是我不明白为什么在我做同样的事情并且没有错误之前会出现错误,我能想到的唯一答案是在同一张表上不可能有两个或多个外键。这是我的迁移功能

class CreateStatusTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('page_status', function($table) {
        $table->increments('id');
        $table->string('status_name');
        $table->integer('status_value')->unsigned();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('page_status');
}

}

这是用于状态表的,现在我必须使用它向页面表添加新字段。

class AddStatusToPagesTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('pages', function($table) {
        $table->integer('page_status')->unsigned();

        $table->foreign('page_status')->references('status_value')->on('page_status');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('pages', function($table) {
        $table->dropForeign('pages_page_status_foreign');
    });
}

}

这就是出现错误的地方,由于某种原因,它不允许我将 page_status 字段上的外键设置到 pages 表中。

我在我的本地主机上使用 xampp 安装,在 phpmyadmin 中我可以看到该表设置为 innodb,实际上默认情况下所有内容都设置为 innodb。在我的数据库中的 pages 表中查看 page_status 字段我必须首先设置它的索引,而不是我能够使用关系。为什么它没有设置为索引我不知道,但我已经将该表 id 作为索引和作者作为外键。

在此之前,我在创建 pages 表并使用它时还添加了一些字段

class CreatePagesTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('pages', function($table){
        $table->increments('id');
        $table->integer('author')->unsigned();
        $table->foreign('author')->references('id')->on('users');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('pages');
}

}

使用迁移时我没有遇到任何问题,它运行良好,并且作者被设置为外键。

那么为什么我现在不能添加新的外键呢?

4

2 回答 2

1

这可能是由于如果当前记录不满足条件,则无法添加外键。如果page_status是可选的,则使该字段可以为空:

$table->integer('page_status')->unsigned()->nullable();

如果您不想让它为空并且稍后要插入有效的外键值,您可以暂时禁用外键检查:

DB::statement('SET FOREIGN_KEY_CHECKS = 0');

Schema::table('pages', function($table) {
    $table->integer('page_status')->unsigned();
    $table->foreign('page_status')->references('status_value')->on('page_status');
});

DB::statement('SET FOREIGN_KEY_CHECKS = 1');
于 2015-01-29T18:15:16.233 回答
0

我发现问题出在哪里,在向表中添加新字段后,您必须在该字段上设置索引,因此在迁移方面还有一步将字段设置为索引。

我仍然不明白为什么在我的第一次迁移中,当我添加“作者”字段时,它会自动将其作为索引,但对于这个我通过另外设置索引使其工作,如下所示:

    Schema::table('pages', function($table) {
        $table->integer('status')->unsigned()->nullable();
        $table->index('status');

        $table->foreign('status')->references('status_value')->on('page_status');
    });
于 2015-01-29T22:25:36.337 回答