首页 > 解决方案 > Laravel - 尝试迁移我创建的新表,但 VS 正在尝试迁移已经迁移的表?

问题描述

我创建了一个表'create_courses_table',但是当我尝试迁移这个新表时,我从我已经迁移的上一个表中收到以下错误:

Migrating: 2020_03_04_141200_create_role_user_pivot_table

   Illuminate\Database\QueryException 

  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'role_user' already exists (SQL: create table `role_user` (`user_id` int unsigned not null, `role_id` int unsigned not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673| 

      +9 vendor frames 
  10  database/migrations/2020_03_04_141200_create_role_user_pivot_table.php:22
      Illuminate\Support\Facades\Facade::__callStatic("create")

      +22 vendor frames 
  33  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

我假设我的数据透视表有错误?我不太确定我做错了什么。它的代码如下:

<?php

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

class CreateRoleUserPivotTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');

            $table->unsignedInteger('role_id');
            $table->foreign('role_id')->references('id')->on('roles');
        });
    }

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

谢谢,任何帮助表示赞赏。

标签: phplaravel

解决方案


根据您对问题的评论,我认为将迁移存储在迁移表中时出了点问题。

在您的数据库上运行以下查询。如果它返回 0,请继续我的回答。如果它返回 1(甚至更多),请忽略我的回答,错误在其他地方:

SELECT COUNT(*) FROM migrations WHERE migration = '2020_03_04_141200_create_role_user_pivot_table';

要解决此问题,您可以手动将迁移添加到表中:

只需在名为 的表中添加一个新元组,列中migrations的文件名(不带.phpergo 2020_03_04_141200_create_role_user_pivot_tablemigration和一个batch比表中的最高值高 1 的 -number。

尔格:这样做:

获取递增的批号:

SELECT MAX(batch)+1 FROM migrations

然后手动插入您的迁移(替换42为上一个查询的结果):

INSERT INTO migrations (migration, batch)
VALUES ('2020_03_04_141200_create_role_user_pivot_table', 42)

推荐阅读