【发布时间】:2019-10-17 14:05:34
【问题描述】:
更新:我现在要放弃外键的东西。似乎我的项目在基本层面上被打破了,所以我稍后会重新审视这个项目。我感谢 cmets 中的两个乐于助人的小伙子。
我正在尝试将外键合并到我的 Laravel 应用程序中,但我一直卡住。我不断收到"errno: 150 "Foreign key constaint is incorrectly formed".
即使在尝试了多种解决方案、删除表、更改迁移顺序等之后,我仍然会遇到此错误。这非常令人沮丧。
我也尝试过php artisan migrate:refresh 和php artisan migrate:reset,但似乎没有任何帮助。
在下面的代码中有一段来自CreateQuestionsTable class的代码
Schema::table('questions', function(Blueprint $table){
$table->foreign('answerTypeName')->references('answerType')->on('answerstypes');
});
我尝试将其放入CreateAnswersTable class,但也没有解决。
在下面的代码中还有一段来自CreateQuestionsTable class的代码
Schema::create('questions', function (Blueprint $table) {
$table->increments('id');
$table->string('questionName');
$table->string('answerTypeName');
$table->timestamps();
});
在这里,我还尝试将 answerTypeName 更改为 answerTypeId 和 $table->integer,但这也没有帮助。
class CreateQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->increments('id');
$table->string('questionName');
$table->string('answerTypeName');
$table->timestamps();
});
Schema::table('questions', function(Blueprint $table){
$table->foreign('answerTypeName')->references('answerType')->on('answerstypes');
});
}
}
class CreateAnswertypesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('answerstypes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('answerType');
$table->timestamps();
});
}
}
这是一个不断弹出的错误
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `impact_dockwize`.`questions` (errno: 150 "Foreign key constraint is incorrectly formed")")
我希望它能够像这样工作,但是当我尝试执行 php artisan migrate 时,错误不断弹出。正如我上面提到的,应用 php artisan migrate:refresh 或 reset 似乎也不起作用。
【问题讨论】:
-
您按什么顺序运行迁移?必须先创建
answerstypes表,然后才能在questions表上创建外键。 -
@Remul
answerstypes表在questions表之前。 -
我想我找到了问题,外键必须引用父表的主键或唯一键。如果您添加
$table->string('answerType')->unique();它应该可以工作。 -
@Remul 感谢您的建议!可悲的是,它首先返回了一个表已经存在的错误,所以我试图删除该表。再次运行
php artisan migrate后,我又回到了与原始线程相同的错误。 -
您是否手动从数据库中删除了
migrations、questions和answerstypes表并尝试再次迁移?我刚刚自己在本地测试了您的迁移,当我添加unique时它可以工作。