我不知道如何使用Laravel框架向现有的数据库表中添加新列。
我试图编辑迁移文件使用…
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer("paid");
});
}
在终端中,我执行了php artisan migrate:install和migrate。
如何添加新列?
我不知道如何使用Laravel框架向现有的数据库表中添加新列。
我试图编辑迁移文件使用…
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer("paid");
});
}
在终端中,我执行了php artisan migrate:install和migrate。
如何添加新列?
当前回答
执行如下命令: 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');
});
}
你能做的就是,
Schema::create('users', function ($table) {$table->integer("paid");});
写完这个写命令后,php artisan迁移或刷新 我个人更喜欢的是刷新而不是新迁移,因为如果你做新迁移,它会删除所有的数据刷新不会。
但唯一的例外是,如果你进行了刷新如果你在表中有任何外键那么它就不会重新建立关系所以你会得到这样的错误,
不能添加外键约束
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');
警告:这是一个破坏性的行动。如果使用这种方法,请确保首先备份数据库。
你可以简单地修改你现有的迁移文件,例如在你的表中添加一个列,然后在你的终端输入:
$ php artisan migrate:refresh
这个东西在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
希望这对你有所帮助。