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

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

<?php

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

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

如何添加新列?


当前回答

你能做的就是,

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

写完这个写命令后,php artisan迁移或刷新 我个人更喜欢的是刷新而不是新迁移,因为如果你做新迁移,它会删除所有的数据刷新不会。

但唯一的例外是,如果你进行了刷新如果你在表中有任何外键那么它就不会重新建立关系所以你会得到这样的错误,

不能添加外键约束

其他回答

你可以像这样在初始的Schema::create方法中添加新列:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

如果您已经创建了一个表,您可以通过创建一个新的迁移并使用Schema::table方法向该表添加额外的列:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

关于这一点,文档相当详尽,从版本3到版本4没有太大的变化。

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

首先回滚之前的迁移

php artisan migrate:rollback

之后,您可以修改现有的迁移文件(添加新列、重命名列或删除列),然后重新运行迁移文件

php artisan migrate

警告:这是一个破坏性的行动。如果使用这种方法,请确保首先备份数据库。

你可以简单地修改你现有的迁移文件,例如在你的表中添加一个列,然后在你的终端输入:

$ php artisan migrate:refresh

如果您想将新列作为外键添加到现有表。

执行命令:make:migration创建新的迁移

例子:

php artisan make:migration add_store_id_to_users_table --table=users

在database/migrations文件夹中,你有一个新的迁移文件,如下所示:

2018_08_08_093431_add_store_id_to_users_table.php(见注释)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddStoreIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            
            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');
            
            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            
            // 1. Drop foreign key constraints
            $table->dropForeign(['store_id']);

            // 2. Drop the column
            $table->dropColumn('store_id');
        });
    }
}

然后执行命令:

php artisan migrate

如果您因为任何原因想要撤消上次迁移,请运行此命令:

php artisan migrate:rollback

您可以在文档中找到更多关于迁移的信息