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

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

<?php

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

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

如何添加新列?


当前回答

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

其他回答

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

php artisan migrate

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

你可以像这样在初始的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没有太大的变化。

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

在拉拉维尔 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

你能做的就是,

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

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

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

不能添加外键约束