laravel数据迁移之migration

2019-07-19  本文已影响0人  大也也

migration 简介

Introduction

Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.

引用laravel官方对migration的唯一一段介绍,从第一句可以看出,migration 是对数据库(在咱们项目中就是mysql)的版本控制。好比git之于code,docker之于镜像,但migration不是laravel独有的, YII2也有,python的主流框架中也有。

migration 相关使用

命令的使用建议还是看官方文档。总结了一下自己平时的使用习惯。

举个例子,比如现在需要在数据库中新建一张支付订单表,并写出对应的Model类方法

步骤顺序如下:

在项目根目录中运行命令

php artisan make:model Models\PayOrder -m

此命令做了两件事情

2019_07_16_232149_create_pay_orders_table

上一步中迁移文件的结构如下

class CreatePayOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pay_orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pay_orders');
    }
}

可以看到,目前为止只运行了一个命令。model类建好了,数据库的名字也已经自动起好了,叫 pay_orders,(系统自动加复数),接下来编写迁移文件,编写后的文件如下

class CreatePayOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pay_orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('company_id')->comment('保险公司ID');
            $table->integer('product_id')->comment('产品ID');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pay_orders');
    }
}

然后运行

php artisan migrate:refresh -path database/migrations/2019_07_16_232149_create_pay_orders_table.php 

会在数据库中生成 pay_orders 表。

熟悉这个流程后,数据库的回滚和填充后续参考官方文档

migration 在小铭保的使用

小铭保1.0快速开发时,因为每个人在负责一个模块,而且时间比较紧急,migration没有统一使用。

小铭保如果现在开启migration ,可以开启配置文件后,运行

php artisan migrate:generate

生成线上数据库表对应的migration文件,相当于sql 的一次 git init 操作

不过,migration 终究只是辅助sql统一开发和线上管理的工具,至于在小铭保以及后续其它laravel项目中的使用,大家可以讨论一下,看看如何取舍

上一篇下一篇

猜你喜欢

热点阅读