6. 数据库版本控制 -migration

2016-06-08  本文已影响447人  ZhouJiping
migrations位置

常用migraiton命令

// 创建表的migration
php artisan make:migration create_users_table --create=users

// 创建model的时候同时生成表的migration
php artisan make:model User -m

// 将表的migration生成到数据库
php artisan migrate

// 撤销上一步的生成
php artisan migration:rollback

// 添加字段到表
php artisan make:migration add_intro_column_to_articles --table=articles  

编辑生成的创建users表的migration文件

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

编辑插入字段到表的migration文件

添加字段到表
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddIntroColumnToArticles extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->string('intro');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function (Blueprint $table) {
            // rollback的时候用
            $table->dropColumn('intro');
        });
    }
}

** 更改字段的名字**

// 先安装doctrine/dbal 包
composer require doctrine/dbal

//然后建立migraiton文件
php artisan make:migraiton alter_intro_column_to_intros_in_articles --table=articles

用法

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AlterIntroColumnToArticles extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->renameColumn('intro', 'intros');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->renameColumn('intros', 'intro');
        });
    }
}

上一篇下一篇

猜你喜欢

热点阅读