laravel5.1 數據庫遷移文件的demo


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('[email protected]')->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');

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章