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

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

<?php

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

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

如何添加新列?


当前回答

警告:这是一个破坏性的行动。如果使用这种方法,请确保首先备份数据库。

你可以简单地修改你现有的迁移文件,例如在你的表中添加一个列,然后在你的终端输入:

$ php artisan migrate:refresh

其他回答

首先回滚之前的迁移

php artisan migrate:rollback

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

php artisan migrate

要创建迁移,您可以在Artisan CLI中使用migrate:make命令。使用特定的名称以避免与现有模型冲突

对于拉拉维尔 5+:

php artisan make:migration add_paid_to_users_table --table=users

对于拉拉维尔 3:

php artisan migrate:make add_paid_to_users

然后需要使用Schema::table()方法(因为您正在访问一个现有的表,而不是创建一个新表)。你可以像这样添加一列:

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

不要忘记添加回滚选项:

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

然后你可以运行你的迁移:

php artisan migrate

Laravel 4 / Laravel 5的文档都很好地介绍了这一点:

模式构建器 迁移

对于Laravel 3:

模式构建器 迁移

编辑:

用表- >美元整数(支付)- >后(“whichever_column”);将此字段添加到特定列之后。

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

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

尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用tinker添加一个列。

$ php artisan tinker

下面是终端的示例一行代码:

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

(这里是为了便于阅读而设置的格式)

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

这个东西在laravel 5.1上工作。

首先,在终端上执行这段代码

php artisan make:migration add_paid_to_users --table=users

然后转到项目目录,展开目录database - migration,编辑文件add_paid_to_users.php,添加这段代码

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

然后返回到您的终端并执行此命令

php artisan migrate

希望这对你有所帮助。