简体   繁体   English

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

[英]Laravel Add a new column to existing table in a migration

I can't figure out how to add a new column to my existing database table using the Laravel framework.我不知道如何使用 Laravel 框架向我现有的数据库表中添加新列。

I tried to edit the migration file using...我尝试使用...编辑迁移文件

<?php

public function up()
{
    Schema::create('users', function ($table) {
        $table->integer("paid");
    });
}

In terminal, I execute php artisan migrate:install and migrate .在终端中,我执行php artisan migrate:installmigrate

How do I add new columns?如何添加新列?

To create a migration, you may use the migrate:make command on the Artisan CLI.要创建迁移,您可以在 Artisan CLI 上使用 migrate:make 命令。 Use a specific name to avoid clashing with existing models使用特定名称以避免与现有模型发生冲突

for Laravel 3:对于 Laravel 3:

php artisan migrate:make add_paid_to_users

for Laravel 5+:对于 Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one).然后,您需要使用Schema::table()方法(因为您正在访问现有表,而不是创建新表)。 And you can add a column like this:您可以添加这样的列:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

and don't forget to add the rollback option:并且不要忘记添加回滚选项:

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}

Then you can run your migrations:然后你可以运行你的迁移:

php artisan migrate

This is all well covered in the documentation for both Laravel 3:这在 Laravel 3 的文档中都有很好的介绍:

And for Laravel 4 / Laravel 5:对于 Laravel 4 / Laravel 5:

Edit:编辑:

use $table->integer('paid')->after('whichever_column');使用$table->integer('paid')->after('whichever_column'); to add this field after specific column.在特定列之后添加此字段。

I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.我将为使用 Laravel 5.1 及更高版本的未来读者添加 mike3875 的答案。

To make things quicker, you can use the flag "--table" like this:为了使事情更快,您可以像这样使用标志“--table”:

php artisan make:migration add_paid_to_users --table="users"

This will add the up and down method content automatically:这将自动添加updown方法内容:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}

Similarily, you can use the --create["table_name"] option when creating new migrations which will add more boilerplate to your migrations.同样,您可以在创建新迁移时使用--create["table_name"]选项,这将为您的迁移添加更多样板。 Small point, but helpful when doing loads of them!小点,但在做大量工作时很有帮助!

laravel 5.6 and above Laravel 5.6 及以上

in case you want to add new column as a FOREIGN KEY to an existing table.如果您想将新列作为外键添加到现有表中。

Create a new migration by executing this command : make:migration通过执行以下命令创建一个新的迁移: make:migration

Example :例子 :

php artisan make:migration add_store_id_to_users_table --table=users

In database/migrations folder you have new migration file, something like :在 database/migrations 文件夹中,您有新的迁移文件,例如:

2018_08_08_093431_add_store_id_to_users_table.php (see the comments) 2018_08_08_093431_add_store_id_to_users_table.php (见评论)

<?php

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

class AddStoreIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');

            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Drop foreign key constraints
            $table->dropForeign(['store_id']);

            // 2. Drop the column
            $table->dropColumn('store_id');
        });
    }
}

After that run the command :之后运行命令:

php artisan migrate

In case you want to undo the last migration for any reason, run this command :如果您出于任何原因想要撤消上次迁移,请运行以下命令:

php artisan migrate:rollback

You can find more information about migrations in the docs您可以在文档中找到有关迁移的更多信息

If you're using Laravel 5, the command would be;如果您使用的是 Laravel 5,则命令为;

php artisan make:migration add_paid_to_users

All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.所有用于制作事物的命令(控制器、模型、迁移等)都已移至make:命令下。

php artisan migrate is still the same though. php artisan migrate仍然是一样的。

You can add new columns within the initial Schema::create method like this:您可以在初始Schema::create方法中添加新列,如下所示:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:如果您已经创建了一个表,您可以通过创建一个新的迁移并使用Schema::table方法向该表添加其他列:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4 .文档对此相当详尽,并且从version 3version 4没有太大变化。

Laravel 7 Laravel 7

  1. Create a migration file using cli command:使用 cli 命令创建迁移文件:

    php artisan make:migration add_paid_to_users_table --table=users

  2. A file will be created in the migrations folder, open it in an editor.将在迁移文件夹中创建一个文件,在编辑器中打开它。

  3. Add to the function up():添加到函数 up():

Schema::table('users', function (Blueprint $table) {
    // Create new column
    // You probably want to make the new column nullable
    $table->integer('paid')->nullable()->after('status');
}
  1. Add to the function down(), this will run in case migration fails for some reasons:添加到函数 down(),这将在迁移因某些原因失败时运行:

    $table->dropColumn('paid');

  2. Run migration using cli command:使用 cli 命令运行迁移:

    php artisan migrate


In case you want to add a column to the table to create a foreign key constraint:如果您想向表中添加一列以创建外键约束:

In step 3 of the above process, you'll use the following code:在上述过程的第 3 步中,您将使用以下代码:

$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');

$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');

In step 4 of the above process, you'll use the following code:在上述过程的第 4 步中,您将使用以下代码:

// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');

this things is worked on laravel 5.1.这些东西在 Laravel 5.1 上有效。

first, on your terminal execute this code首先,在您的终端上执行此代码

php artisan make:migration add_paid_to_users --table=users

after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code之后转到您的项目目录并展开目录数据库 - 迁移和编辑文件 add_paid_to_users.php,添加此代码

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

after that go back to your terminal and execute this command之后返回您的终端并执行此命令

php artisan migrate

hope this help.希望这有帮助。

In Laravel 8在 Laravel 8

php artisan make:migration add_columnname_to_tablename_table --table=tablename

then after creating migration in然后在创建迁移之后

public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            $table->datatype('column_name')->nullable();
        });
    }
public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            $table->dropColumn('column_name');
        });
    }

then run然后运行

php artisan migrate

if you face error then rename the migration name with the date before the table created and then run again php artisan migrate如果您遇到错误,请使用创建表之前的日期重命名迁移名称,然后再次运行php artisan migrate

WARNING this is a destructive action.警告这是一个破坏性的行为。 If you use this ensure you back up your database first如果您使用它,请确保首先备份您的数据库

you can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :您可以简单地修改现有的迁移文件,例如在表中添加一列,然后在终端中输入:

$ php artisan migrate:refresh

First rollback your previous migration首先回滚之前的迁移

php artisan migrate:rollback

After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file之后,您可以修改现有的迁移文件(添加新的、重命名或删除列),然后重新运行您的迁移文件

php artisan migrate

将列添加到您的迁移文件并运行此命令。

php artisan migrate:refresh --path=/database/migrations/your_file_name.php

Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.尽管正如其他人提到的那样,迁移文件是最佳实践,但在紧要关头,您还可以添加一个包含 tinker 的列。

$ php artisan tinker

Here's an example one-liner for the terminal:这是终端的单行示例:

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })



(Here it is formatted for readability) (这里是为了可读性而格式化的)

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ 
    $table->integer('paid'); 
});

First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command for Laravel 4:首先你必须创建一个迁移,你可以在 laravel artisan CLI 上使用 migrate:make 命令。像 laravel 4 这样的旧 laravel 版本你可以在 Laravel 4 上使用这个命令:

php artisan migrate:make add_paid_to_users

And for laravel 5 version而对于 Laravel 5 版本

for Laravel 5+:对于 Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

Then you need to use the Schema::table() .然后你需要使用 Schema::table() 。 And you have to add the column:你必须添加列:

public function up()

{

    Schema::table('users', function($table) {

        $table->integer('paid');

    });

}

further you can check this你可以进一步检查这个

If you don't want to split the blueprint(schema) into two migration file then the best thing you can do is drop the table from the database and then rename the migration file's last number and do如果您不想将蓝图(架构)拆分为两个迁移文件,那么您可以做的最好的事情是从数据库中删除该表,然后重命名迁移文件的最后一个编号并执行

php artisan migrate

This helps you to protect the data of other tables.这有助于您保护其他表的数据。

运行此命令: php artisan migrate:fresh --seed 它将删除表并重新添加它更新添加到数据库的所有列

What you can do is Like,你可以做的是像,

Schema::create('users', function ($table) { $table->integer("paid"); });

After Writing this write command php artisan migrate or php artisan refresh What i personally prefer is to refresh rather than fresh migration because if you do fresh migrate it will remove all the data refresh will not.在编写此写入命令php artisan migratephp artisan refresh我个人更喜欢刷新而不是新迁移,因为如果您执行新迁移,它将删除所有数据,刷新不会。

but only exception is if you do refresh and if you have any foreign key in table so it will not going to re-establish the relationship so you will get error like,但唯一的例外是,如果您进行刷新并且表中有任何外键,则它不会重新建立关系,因此您会收到类似错误,

Cannot add foreign key constrain无法添加外键约束

In laravel 8在 laravel 8

php artisan make:migration add_paid_to_users_table --table=users

public function up()
 {
    Schema::table('users', function($table) {

        $table->integer('paid');

  });

} }

In laravel 9在 laravel 9

  add a new column in existing table

  php artisan make:migration add_paid_to_users_table

if you want to create new migration then do the below code

  php artisan make:migration create_users_table --create=users

just edit in migration file what you want to add a new column and run -->只需在迁移文件中编辑要添加新列的内容并运行 -->

php artisan migrate:refresh php工匠迁移:刷新

If none of the solve worked, you might have recreated the migration file then added a new column and tried to run php artisan migrate to update the old table which will try to create that table but the table already exists so it gives an error.如果解决方案都不起作用,您可能已经重新创建了迁移文件,然后添加了一个新列并尝试运行php artisan migrate以更新旧表,该表将尝试创建该表,但该表已经存在,因此会出错。 To solve that rename the migration file as previously named (started with a date), then add new column run php artisan migrate that will actually update the old one instead of create, solved my problem.要解决将迁移文件重命名为以前命名的问题(以日期开头),然后添加新列运行php artisan migrate ,它实际上会更新旧的而不是创建,解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM