首页 > 代码库 > laravel5.1 数据库迁移文件的demo

laravel5.1 数据库迁移文件的demo

<?php

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

class Artical extends Migration
{
    // 此方法为自己找的一个判断数据库索引是否存在,$table表名,$name索引名,可在此文件中调用使用
    public function hasIndex($table, $name)
    {
        $conn = Schema::getConnection();
        $dbSchemaManager = $conn->getDoctrineSchemaManager();
        $doctrineTable = $dbSchemaManager->listTableDetails($table);
        return $doctrineTable->hasIndex($name);
    }
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //创建表文章表
       if (!Schema::hasTable(‘article‘)) {//判断article表是否存在
            Schema::create(‘article‘,function(Blueprint $table){
                  $table->increments(‘id‘);
                  $table->string(‘email‘)->default(‘123456@qq.com‘)->nullable()->comment(‘邮箱‘);
                  $table->char(‘password‘,16)->comment(‘密码‘);
                  $table->string(‘title‘)->comment(‘标题‘);
                  $table->timestamps();//添加一个创建时间的字段和一个修改时间的字段
                  $table->rememberToken();
                  $table->engine = ‘MyISAM‘;
            });
        }else{
            // 2016/3/5 高山
            if (!Schema::hasColumn(‘article‘, ‘sex‘)) {//判断列是否存在,不存在则创建此列
                Schema::table(‘article‘, function ($table) {
                    $table->tinyInteger(‘sex‘)->default(‘1‘)->comment(‘性别‘);
                });
             }
            // 2016/3/7 高山
            if(Schema::hasColumn(‘article‘, ‘title‘)) {//判断列如果存在则修改其字段的属性
                Schema::table(‘article‘, function ($table) {
                    $table->text(‘title‘)->change();
                });
            }
             // 2016/3/9 高山
            if(Schema::hasColumn(‘article‘, ‘remember_token‘)){//如果article表中有remember_token列则删除
                 Schema::table(‘article‘, function ($table) {
                    $table->dropColumn(‘remember_token‘);
                });
            }


        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //删除文章表
        //Schema::drop(‘article‘);

    }
}

本文出自 “高山” 博客,谢绝转载!

laravel5.1 数据库迁移文件的demo