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

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

<?php

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

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

如何添加新列?


当前回答

在拉拉维尔 8

php artisan make:migration add_paid_to_users_table --table=users

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

        $table->integer('paid');

  });

}

在laravel

在现有表中添加新列

php artisan make:migration add_paid_to_users_table

如果您想创建新的迁移,那么执行下面的代码

php artisan make:migration create_users_table --create=users

其他回答

这个东西在laravel 5.1上工作。

首先,在终端上执行这段代码

php artisan make:migration add_paid_to_users --table=users

然后转到项目目录,展开目录database - migration,编辑文件add_paid_to_users.php,添加这段代码

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

然后返回到您的终端并执行此命令

php artisan migrate

希望这对你有所帮助。

尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用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'); 
});

步骤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

然后您将添加一个新列

在拉拉维尔 8

php artisan make:migration add_paid_to_users_table --table=users

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

        $table->integer('paid');

  });

}

在laravel

在现有表中添加新列

php artisan make:migration add_paid_to_users_table

如果您想创建新的迁移,那么执行下面的代码

php artisan make:migration create_users_table --create=users

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

    });

}