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

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

<?php

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

在终端中,我执行了php artisan migrate:install和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”);将此字段添加到特定列之后。

其他回答

要创建迁移,您可以在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”);将此字段添加到特定列之后。

尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用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'); 
});

如果这些解决方案都不起作用,您可能已经重新创建了迁移文件,然后添加了一个新列,并尝试运行php artisan migrate来更新旧表,它将尝试创建这个表,但这个表已经存在,所以它会给出一个错误。为了解决这个问题,将迁移文件重命名为以前命名的(以日期开始),然后添加新的列运行php artisan migrate,这实际上会更新旧的而不是创建,解决了我的问题。

执行如下命令: PHP工匠迁移:新鲜——种子 它将删除表并重新添加它,更新添加到数据库的所有列

在拉拉维尔 8

php artisan make:migration add_paid_to_users_table --table=users

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

        $table->integer('paid');

  });

}

在laravel

在现有表中添加新列

php artisan make:migration add_paid_to_users_table

如果您想创建新的迁移,那么执行下面的代码

php artisan make:migration create_users_table --create=users