首页 > 解决方案 > 当我尝试在 laravel 中迁移我的表时,我不断收到以下错误

问题描述

我试图运行 php artisan migrate 但我不断收到以下错误:

我试图回滚表并再次迁移它们,但它只是给了我同样的错误

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on delete cascade)

这是我的 create_comments_table:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCommentsTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->mediumText('body');
        $table->string('email');
        $table->string('name');
        $table->boolean('approved');
        $table->integer('post_id')->unsigned();
        $table->timestamps();

    });

    Schema::table('comments', function ($table) {
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
    });

}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropforeign(['post_id']);
    Schema::dropIfExists('comments');
}
}

这是我的 create_posts_table:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->mediumText('body');
        $table->string('name');
        $table->timestamps();
    });
}

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

我的迁移表是按以下顺序创建的:

create users table
create passwords 
create failed jobs
create posts 
create comments

我怎样才能解决这个问题?

标签: phplaravellaravel-artisanartisan-migrate

解决方案


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCommentsTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->mediumText('body');
        $table->string('email');
        $table->string('name');
        $table->boolean('approved');
        $table->integer('post_id')->unsigned();
        $table->timestamps();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
    });
}

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

尝试更新评论像这样迁移文件


推荐阅读