且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Laravel迁移中将新列添加到现有表

更新时间:2021-12-31 07:06:34

如果检查错误跟踪:

基本表或视图已存在:1050表用户"已存在

Base table or view already exists: 1050 Table 'users' already exists

这意味着用户表已经存在,因此在您进行迁移时,它试图创建一个已经在数据库中创建的表.

This means that the users table already exists so when you run your migrations it is trying to create a table that is already created in your database.

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

Note: Don't forget to backup your database first

删除用户表,还会从迁移表中删除用户条目.

Delete users table from the database also delete users entries from migrations table.

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

After, execute the migrate Artisan command:php artisan migrate

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

Now another your Question is: How to add new columns in my existing table?

您必须使用以下命令创建表:

You have to create a table using this command:

php artisan make:migration create_users_table

您得到的输出是这样的:创建的迁移:2019_04_12_070152_create_users_table

The output you got it like this: Created Migration: 2019_04_12_070152_create_users_table

您的迁移结构是这样的:

Your Migration structure is something this:

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()方法(因为您正在访问现有表,而不是创建新表).您可以添加这样的列:

use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:

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

After, you can run your migrations: php artisan migrate

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

Your new columns(phonenumber) are now added to your existing users table, which you can view in your database.

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

If you have still any doubt, see this video