【问题标题】:Even if i migrate:fresh it shows me that the table already exists.. why?即使我 migrate:fresh 它告诉我该表已经存在..为什么?
【发布时间】:2021-12-22 03:41:49
【问题描述】:

所以我想php artisan migrate:fresh 但我收到此错误

基表或视图已存在:1050 表“角色”已存在

即使我从 phpmyadmin 删除数据库,清理缓存并再次创建数据库,它仍然显示相同的消息,表行的迁移如下:

<?php

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

class CreateRolesTable extends Migration
{
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->tinyInteger('status');
        });
    }

    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

显示的完整错误:

SQLSTATE[42S01]:基表或视图已存在:1050 表“角色”已存在(SQL:创建表 roles (id bigint unsigned not null auto_increment 主键,name varchar(255) not null, guard_name varchar(255) not null, created_at timestamp null, updated_at timestamp null) 默认字符集 utf8mb4 collat​​e 'utf8mb4_unicode_ci')

这是为什么呢?我可以或应该做什么?

【问题讨论】:

  • 是否正在运行不同的迁移来创建表?
  • 不,这不是我所知道的,我现在会重新检查
  • 不,不是另一个正在运行的迁移创建它
  • hmmm,您是否正在使用可能创建该表的包?你能复制/粘贴你的php artisan migrate:fresh 命令的输出吗?是否成功创建之前的其他表(检查 phpMyAdmin)?确定你删除了正确的数据库?删除 db 后你运行 php artisan migrate:install 了吗?
  • 我更新了它并且我使用了一些来自 spatie 的权限并且它在安装这个包之前工作但即使这样它也不应该工作如果我迁移:像删除所有表并创建新表一样新鲜?

标签: mysql laravel database migration


【解决方案1】:

首先使用此代码 Schema::dropIfExists('roles'); 删除 roles 表,然后创建。

<?php

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

class CreateRolesTable extends Migration
{
    public function up()
    {
        Schema::dropIfExists('roles'); //added
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->tinyInteger('status');
        });
    }

    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

【讨论】:

    【解决方案2】:

    如果它在您进行工匠迁移之前已经存在,它当然会这样说。您是否进行了迁移,并且中途中断了?您可以重置它或只是删除表并重试(如果您在本地开发中并且可以删除它)。

    php 工匠迁移:重置

    【讨论】: