我不知道如何使用Laravel框架向现有的数据库表中添加新列。

我试图编辑迁移文件使用…

<?php

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

在终端中,我执行了php artisan migrate:install和migrate。

如何添加新列?


当前回答

你可以像这样在初始的Schema::create方法中添加新列:

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

如果您已经创建了一个表,您可以通过创建一个新的迁移并使用Schema::table方法向该表添加额外的列:

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

关于这一点,文档相当详尽,从版本3到版本4没有太大的变化。

其他回答

向迁移文件中添加列并运行此命令。

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

如果您正在使用Laravel 5,命令将是;

php artisan make:migration add_paid_to_users

所有用于制作东西的命令(控制器、模型、迁移等)都被移动到make:命令下。

PHP工匠迁移仍然是一样的。

在拉拉维尔 8

php artisan make:migration add_columnname_to_tablename_table --table=tablename

然后在创建迁移之后

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');
        });
    }

然后运行

php artisan migrate

如果遇到错误,则用创建表之前的日期重命名迁移名称,然后再次运行PHP artisan migrate

我将添加到mike3875的答案,供将来使用Laravel 5.1及后续版本的读者使用。

为了让事情变得更快,你可以像这样使用标志"——table":

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

这将自动添加up和down方法内容:

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

类似地,您可以在创建新的迁移时使用——create["table_name"]选项,这将为您的迁移添加更多的样板。这是个小问题,但在做大量的事情时很有帮助!

首先回滚之前的迁移

php artisan migrate:rollback

之后,您可以修改现有的迁移文件(添加新列、重命名列或删除列),然后重新运行迁移文件

php artisan migrate