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

我试图使用...来编辑迁移文件。

<?php

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

在终端中,我执行php artisan migrate:installmigrate

如何添加新列?

最佳答案

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

对于Laravel 3:

php artisan migrate:make add_paid_to_users

对于Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=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 3的文档都对此进行了详细介绍:
  • Schema Builder
  • Migrations

  • 对于Laravel 4/Laravel 5:
  • Schema Builder
  • Migrations

  • 编辑:

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

    09-10 21:21
    查看更多