laravel 数据迁移小结

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']);
        });
    }
}

如果哪位大佬发现有问题,请及时联系我,谢谢

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值