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

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

<?php

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

在终端中,我执行了php artisan migrate:install和migrate。

如何添加新列?


当前回答

如果您不想将蓝图(模式)拆分为两个迁移文件,那么最好的方法是从数据库中删除表,然后重命名迁移文件的最后一个数字

php artisan migrate

这有助于保护其他表的数据。

其他回答

首先你必须创建一个迁移,你可以在laravel artisan CLI上使用migrate:make命令。旧的laravel版本,比如laravel 4,你可以使用这个命令 Laravel 4:

php artisan migrate:make add_paid_to_users

和laravel 5版本

对于拉拉维尔 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');

    });

}

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

在拉拉维尔 8

php artisan make:migration add_columnname_to_tablename_table --table=tablename

然后在创建迁移之后

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

            // 1. Create new column
            $table->datatype('column_name')->nullable();
        });
    }
public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            $table->dropColumn('column_name');
        });
    }

然后运行

php artisan migrate

如果遇到错误,则用创建表之前的日期重命名迁移名称,然后再次运行PHP artisan migrate

Laravel 7

使用cli命令创建迁移文件: PHP工匠使:迁移add_paid_to_users_table——table=用户 将在migrations文件夹中创建一个文件,在编辑器中打开它。 添加到函数up():

Schema::table('users', function (Blueprint $table) {
    // Create new column
    // You probably want to make the new column nullable
    $table->integer('paid')->nullable()->after('status');
}

添加到函数down()中,它将在迁移由于某些原因失败时运行: 表- > dropColumn(“支付”); 使用cli命令执行migration: PHP工匠迁移


如果你想在表中添加一个列来创建一个外键约束:

在上述过程的第3步中,您将使用以下代码:

$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');

$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');

在上述过程的第4步中,您将使用以下代码:

// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');

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