当我 运行 php artisan migrate 命令时出错

Error when I run php artisan migrate command

我正在尝试在我的博客应用程序上添加评论系统,但是在尝试 运行 评论迁移时出现此错误,这似乎与我当前的 comments 迁移文件无关,但是之前的 post_tag 迁移文件

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'post_tag' already exists (SQL:
    create table `post_tag` (
      `id` int unsigned not null  auto_increment primary key,
      `post_id` int unsigned not null, 
      `tag_id` int unsigned not null
    ) default character set utf8 collate utf8_unicode_ci) 

这是我的 comments 迁移文件

<?php

//2017_01_16_101128_create_comments_table.php

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

class CreateCommentsTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->text('comment');
        $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::drop('comments');
}
}

这是我的 post_tag 迁移文件

<?php

2016_12_18_230831_create_post_tag_table.php

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

class CreatePostTagTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id')->unsigned();
        $table->foreign('post_id')->references('id')->on('posts');
        $table->integer('tag_id')->unsigned();
        $table->foreign('tag_id')->unsigned();
    });
}

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

如何消除此错误或我在这里遗漏了什么?

您必须在 mysql 中手动删除 table:

mysql> drop table post_tag;

然后运行再次迁移

php artisan migrate

在您的 CreatePostTagTable 迁移中,您可能不会更改

$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->unsigned();

$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tag');

存在重复。

然后手动删除post_tagtable。它本可以再次创建。您可能还想检查数据库中的 migration table,因为可能有记录。 post_tagtable。如果是这样删除它。然后你就可以 运行 安全地迁移了。

此外,由于您正在创建 pivot table,因此您可能不需要 $table->increments('id');。这可能取决于你的情况。在大多数情况下你不需要它。

我认为你应该试试这个:

Drop table post_tag;

AND

migrations table

中删除 post_tag 迁移

运行 迁移后

php artisan migrate

希望这对你有用!