我知道这已经被回答了很多次,因为我在写这个问题时看到了很多答案建议,但没有一个真正让我得到正确的答案。
当我尝试向表中添加新字段并在 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');
}
}
使用迁移时我没有遇到任何问题,它运行良好,并且作者被设置为外键。
那么为什么我现在不能添加新的外键呢?