我不知道如何使用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。
如何添加新列?
当前回答
尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用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');
});
其他回答
尽管正如其他人所提到的,迁移文件是最佳实践,但在必要时,您也可以使用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');
});
我将添加到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"]选项,这将为您的迁移添加更多的样板。这是个小问题,但在做大量的事情时很有帮助!
如果您不想将蓝图(模式)拆分为两个迁移文件,那么最好的方法是从数据库中删除表,然后重命名迁移文件的最后一个数字
php artisan migrate
这有助于保护其他表的数据。
首先你必须创建一个迁移,你可以在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');
});
}
如果您正在使用Laravel 5,命令将是;
php artisan make:migration add_paid_to_users
所有用于制作东西的命令(控制器、模型、迁移等)都被移动到make:命令下。
PHP工匠迁移仍然是一样的。