Laravel在迁移中向现有表添加新列 [英] Laravel Add a new column to existing table in a migration

查看:58
本文介绍了Laravel在迁移中向现有表添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试使用.

编辑迁移文件
<?php

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

在终端执行php artisan migrate:installmigrate

如何添加新列?

推荐答案

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

这篇关于Laravel在迁移中向现有表添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆