我不知道如何使用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。
如何添加新列?
当前回答
你能做的就是,
Schema::create('users', function ($table) {$table->integer("paid");});
写完这个写命令后,php artisan迁移或刷新 我个人更喜欢的是刷新而不是新迁移,因为如果你做新迁移,它会删除所有的数据刷新不会。
但唯一的例外是,如果你进行了刷新如果你在表中有任何外键那么它就不会重新建立关系所以你会得到这样的错误,
不能添加外键约束
其他回答
我将添加到mike3875的答案,供将来使用Laravel 5.1及后续版本的读者使用。
为了让事情变得更快,你可以像这样使用标志"——table":
php artisan make:migration add_paid_to_users --table="users"
这将自动添加up和down方法内容:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
类似地,您可以在创建新的迁移时使用——create["table_name"]选项,这将为您的迁移添加更多的样板。这是个小问题,但在做大量的事情时很有帮助!
这个东西在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
希望这对你有所帮助。
在拉拉维尔 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
尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用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
然后您将添加一个新列