在Laravel中的迁移中向现有表添加新列

9

我希望在laravel中现有的表users中添加一些新列。

我已经通过谷歌搜索并遵循那些搜索结果,使用命令php artisan make:migration add_columns_to_users已创建迁移。

add_columns_to_users.php

public function up()
{
    Schema::table('users', function($table) {
        $table->string('address');
        $table->string('city');
        $table->string('tribe');
        $table->string('country');
        $table->integer('student_id');
        $table->string('tribe_university_name');
        $table->string('student_program_of_study');
        $table->string('faculty');
        $table->string('level');
    });
}

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('address');
        $table->dropColumn('city');
        $table->dropColumn('tribe');
        $table->dropColumn('country');
        $table->dropColumn('student_id');
        $table->dropColumn('tribe_university_name');
        $table->dropColumn('faculty');
        $table->dropColumn('level');
    });
}

创建后,我运行了这个命令 php artisan migrate。但是出现了同样的错误:

基础表或视图已经存在:1050 错误信息 'users' 已经存在 (SQL: create table users (id int unsigned not null auto_increment primary key, name varchar(255) not null, email varchar(255) not null, password varchar(255) not null, remember_token varchar(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8 collate utf8_unicode_ci)

用户表的完整名称是 2014_10_12_000000_create_users_table.php,另一个名称是 2019_04_11_074552_add_column_to_users.php 如何解决?
我的主要问题是如何在现有表中添加新列?

你可以发布初始用户表迁移和新表的完整文件名吗? - thisiskelvin
@thisiskelvin....我已经更新了我的帖子...请查看。 - Arafat Rahman
每当您想在表中添加新列时,最好的做法是编写一个新的迁移。在这种情况下,您需要编写迁移 add_column_to_users --table=users ,然后在迁移中添加列名并运行 php artisan migrate。 - ahmad izhar
请确保您的迁移类名称为 addColumnToUser - Zakaria Acharki
@ZakariaAcharki... 是的,它是 AddColumnToUsers - Arafat Rahman
6个回答

20

如果你查看错误跟踪:

基础表或视图已存在:1050 表 'users' 已经存在

这意味着users表已经存在,因此当你运行迁移时,它试图创建一个已经存在于数据库中的表。

注意: 不要忘记先备份数据库

从数据库中删除users表,并且从migrations表中删除用户条目。

之后,执行迁移Artisan命令:php artisan migrate


现在另一个问题是:如何在我的现有表中添加新列?

你需要使用以下命令创建一个表:

php artisan make:migration create_users_table

你得到的输出是这样的:Created Migration: 2019_04_12_070152_create_users_table

你的迁移结构如下:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

现在您想要在现有用户表中添加新列。

php artisan make:migration add_phone_number_to_users_table --table=users

要访问现有表格而不是创建新表格,可以使用Schema::table()方法。您可以像这样添加列:

public function up()
{
     Schema::table('users', function (Blueprint $table) {
         $table->string('phonenumber')->after('name'); // use this for field after specific column.
     });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('phonenumber');
    });
}

之后,您可以运行迁移:php artisan migrate

您的新列(phonenumber)现在已添加到您现有的用户表中,您可以在数据库中查看它们。

如果您仍有疑问,请参考此视频


1

请执行第一步。

php artisan migrate:reset

第二步:使用PHPmyadmin(或类似工具)进入您的数据库并删除所有剩余的表格,

  • 包括迁移表。

完成后,请执行第三步 php artisan migrate


7
这真是一项很棒的实践。想象一下,如果Facebook决定添加新的字段,比如“is_developer”,然后他们不得不重置所有用户。聪明的做法。 - Benjamin Beganović
我有一个更聪明和更简单的解决方案...删除数据库并运行php artisan migrate..哈哈哈 @BenjaminBeganović - Francesco Taioli
@BenjaminBeganović 当然,只需执行 php artisan db:wipe 然后执行 php artisan migrate --seed 来添加新内容。 - francisco

1
问题出在 php artisan migrate,当2014_10_12_000000_create_users_table.php已经迁移时,它将尝试同时迁移这两个文件,因此我认为有两种可能的解决方案:
  1. 从数据库中回滚 users表并重新运行迁移命令。
  2. migrations表中添加迁移名称,这样命令就不会尝试第二次运行它。

你现在做了什么?这是我们日常工作中可能遇到的一个简单问题,你不必再浪费时间了... 修复它并继续前进。 - Zakaria Acharki

1

修改当前迁移不起作用,因为它在migration表中的条目已经存在。所以要对已经存在的表进行任何更改,您需要创建新的迁移脚本。

// remember `create` replaced by `table` here  

Schema::table('users', function (Blueprint $table) { 
    // add whichever new columns you want to
});

请按照以下步骤操作:
  1. php artisan make:migrate modify_user_table
  2. database/migrations目录下打开modify_user_table文件
  3. 按照我在顶部写的添加新列。

  4. 添加新列后将文件保存到新的迁移文件中。

  5. cmd -> php artisan migrate

编辑

  1. 如果没有用户数据,则打开2014_10_12_000000_create_users_table.php文件,在Schema::create('users'...行之前添加Schema::dropIfExists('users');

  2. 如果有数据,则可以备份,然后再执行步骤1。


这篇帖子没有解决原帖作者的问题。 - Zakaria Acharki
@ZakariaAcharki 你能详细说明为什么吗?这是我们遵循的流程,用于在已迁移的表中添加新列。这是一个完美且已经过测试的流程。 - Rahul
明白了,伙计!我会看看我能做什么。谢谢 :) - Rahul
@RahulMeshram...这是一个糟糕的解决方案:(... 实际上我不想这样做...这就是为什么一直尝试的原因。 - Arafat Rahman
如果什么都不起作用,那就是我提到的原因。但仍然要检查是否还有任何努力或替代方案可尝试。最后再这样做。因为有时候它就像百慕大三角一样难以理解 :) - Rahul
显示剩余2条评论

1

你需要在你的artisan命令中进行一些小的修改

artisan make:migration add_columns_to_users_table

你需要使用Schema::table()方法(因为你正在访问一个已存在的表格,而不是创建一个新的)。你可以像这样添加一列。
  public function up()
  {
     Schema::table('users', function($table) {
          $table->type('column');
      });
   }

添加回滚选项:
 public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('column');
    });
 }

然后你可以运行你的迁移:
 php artisan migrate

0

你可能会遇到这个错误,因为你试图创建另一个已经存在于数据库中的Users表。这可能是你发现错误Base table or view already exists: 1050 Table 'users' already exists的原因。

所以,解决方案是尝试修改你现有的Users表,而不是运行另一个语法来创建和覆盖Users表。通过在数据迁移文件夹中创建另一个alter class。它应该在你的Laravel项目的modules文件夹中(../database/migrations/)。

  • 找到目录后,创建新的alter类。例如,alter_users_table.php
  • 如果你想在Users表上添加另一列(例如:age列,类型为int,可为空),你可以在alter_users_table.php中编写以下代码:

class AlterUsersAddAge extends Migration
{
    /**
     * 运行迁移。
     *
     * @return void
     */
    public function up()
    {
        Schema::table('Users', function (Blueprint $table) {
            $table->int('age')->nullable();
        });
    }

    /**
     * 撤销迁移。
     *
     * @return void
     */
    public function down()
    {
        Schema::table('Users', function (Blueprint $table) {
            $table->dropColumn('age');
        });
    }
}
  • 然后,在终端上运行php artisan migrate
  • 现在,您应该在Users表中看到另一个新列age


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接