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

13 浏览
0 Comments

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

我无法弄清如何使用Laravel框架向现有的数据库表添加新列。

我尝试编辑迁移文件使用...

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

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

我如何添加新列?

admin 更改状态以发布 2023年5月21日
0
0 Comments

我会在mike3875的答案基础上为使用Laravel 5.1及以上版本的读者添加内容。

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

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

这将自动添加 updown 方法内容:

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

同样地,当创建新的迁移时,你可以使用 --create["table_name"] 选项,这将向你的迁移中添加更多样板代码。虽然细小,但在做大量操作时很有帮助!

0
0 Comments

要创建迁移,你可以在 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'); 在特定列后添加这个字段。

0