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

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

<?php

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

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

如何添加新列?


当前回答

执行如下命令: PHP工匠迁移:新鲜——种子 它将删除表并重新添加它,更新添加到数据库的所有列

其他回答

尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用tinker添加一个列。

$ php artisan tinker

下面是终端的示例一行代码:

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })

(这里是为了便于阅读而设置的格式)

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ 
    $table->integer('paid'); 
});

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

步骤1

php artisan make:migration add_sex_to_users_table --table=users

步骤2

在新生成的迁移文件中,您将发现up和down钩子方法。在上勾中,添加你想要添加的列,在下勾中,添加你需要删除的列。例如,我需要在用户列上添加性,所以我将在向上钩添加下面的行。

$table->integer('quantity')->default(1)->nullable();

就像这样

public function up()
{
    Schema::table('service_subscriptions', function (Blueprint $table) {
        $table->integer('quantity')->default(1)->nullable();
    });
}

步骤3

执行如下迁移命令

php artisan migrate

然后您将添加一个新列

如果您正在使用Laravel 5,命令将是;

php artisan make:migration add_paid_to_users

所有用于制作东西的命令(控制器、模型、迁移等)都被移动到make:命令下。

PHP工匠迁移仍然是一样的。

首先你必须创建一个迁移,你可以在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');

    });

}