laravel 数据迁移小结
业务背景:
新增数据表和字段时,需要将Sql语句发给运维来执行,现要求在上线时,一条命令执行所有需新增修改删除的表和字段,这时就用上了laravel的数据迁移功能了,接下来重点阐述具体的流程:
新建数据表
执行命令:
php artisan make:migration create_users_table
create_users_table为PHP文件名称
users为新建的表名称
添加字段:
执行命令:
php artisan make:migration add_votes_to_users_table
文件中会有2个方法:up 和 down
Up为新增方法用于添加新的数据表, 字段或者索引到数据库
Down为撤回up的操作
字段的类型就不再赘述了,laravel官方文档写的很清楚,有需要可以移步这里
执行迁移命令:
php artisan migrate
如果执行完成后需要回滚最后一次迁移,可执行以下命令:
php artisan migrate:rollback
如果需要回滚最近n次的迁移,则命令可以这样写:
php artisan migrate:rollback --step=n
如需回滚所有迁移,则执行以下命令:
php artisan migrate:reset
下面是我自己写的方法:
新增表结构:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUserGiftCardsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_gift_cards', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->nullable();
$table->unsignedInteger('order_id')->nullable();
$table->tinyInteger('status')->default(0);
$table->double('price',8, 2);
$table->timestamp('overdue_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('user_gift_cards');
}
}
修改表结构:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddVipAndGiftCardDeductionPriceToOrderGoodsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('order_goods', function (Blueprint $table) {
$table->double('vip_deduction_price', 8, 2);
$table->double('gift_card_deduction_price', 8, 2);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('order_goods', function (Blueprint $table) {
$table->dropColumn(['vip_deduction_price', 'gift_card_deduction_price']);
});
}
}
如果哪位大佬发现有问题,请及时联系我,谢谢