Laravel迁移表已经存在,但我想添加新的而不是旧的

2022-08-30 08:40:17

我之前创建了用户表。现在,我创建了一个新的迁移,以在我的架构中创建新的书籍表。当我尝试运行该命令时

php artisan migrate

它显示:

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists (SQL: create table `users` (`id` int unsigned not null auto_incr
ement primary key, `username` varchar(255) not null, `email` varchar(255) n
ot null, `password` varchar(255) not null, `created_at` timestamp default 0
 not null, `updated_at` timestamp default 0 not null) default character set
 utf8 collate utf8_unicode_ci)

这是我的新迁移表:

<?php

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

class CreateBooksTable extends Migration {
    public function up()
    {
        Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('books');
    }
}

如何摆脱错误?


答案 1

在 v5.x 中,您可能仍然会遇到此问题。因此,请尝试先使用手动删除相关表

php artisan tinker

然后

Schema::drop('books')

(并退出q)

现在,您可以成功和.php artisan migrate:rollbackphp artisan migrate

如果这种情况反复发生,则应检查迁移中的方法是否显示正确的表名。(如果您更改了表名,则可能是一个陷阱。down()


答案 2

您需要运行

php artisan migrate:rollback

如果这也失败了,只需进入并删除所有表,您可能需要这样做,因为似乎您的迁移表已混乱,或者当您运行上一次回滚时,您的用户表没有删除表。

编辑:

发生这种情况的原因是您之前运行了回滚,并且代码中存在一些错误或未删除表。然而,这仍然搞砸了laravel迁移表,就它而言,您现在没有将用户表向上推送的记录。但是,用户表已存在,并且会引发此错误。


推荐