且构网

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

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

更新时间:2022-04-04 18:50:18

若要创建迁移,可以在Artisan CLI上使用Migrate:Make命令。使用特定名称以避免与现有模型冲突

对于Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

对于Laravel 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:

编辑:

使用$table->integer('paid')->after('whichever_column');将此字段添加到特定列之后。