《PHP實戰(zhàn):Laravel 5框架學(xué)習(xí)之?dāng)?shù)據(jù)庫遷移(Migrations)》要點:
本文介紹了PHP實戰(zhàn):Laravel 5框架學(xué)習(xí)之?dāng)?shù)據(jù)庫遷移(Migrations),希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實例database migrations 是laravel最強(qiáng)大的功能之一.數(shù)據(jù)庫遷移可以理解為數(shù)據(jù)庫的版本控制器.
PHP實例在 database/migrations 目錄中包含兩個遷移文件,一個建立用戶表,一個用于用戶暗碼重置.
PHP實例在遷移文件中,up 辦法用于創(chuàng)建數(shù)據(jù)表,down辦法用于回滾,也就是刪除數(shù)據(jù)表.
PHP實例執(zhí)行數(shù)據(jù)庫遷移
PHP實例查看mysql數(shù)據(jù)庫,可以看到產(chǎn)生了三張表. migratoins 表是遷移記錄表,users 和 pasword_resets.
PHP實例如果設(shè)計有問題,執(zhí)行數(shù)據(jù)庫回滾
PHP實例再次查看mysql數(shù)據(jù)庫,就剩下 migrations 表了, users password_resets 被刪除了.
PHP實例修改遷移文件,再次執(zhí)行遷移.
PHP實例新建遷移
PHP實例在 database/migrations 下生成了新的文件.
PHP實例
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('articles');
}
}
PHP實例自動添加了 id列,自動增長,timestamps() 會自動產(chǎn)生 created_at 和 updated_at 兩個時間列.我們添加一些字段:
PHP實例
public function up()
{
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamp('published_at');
$table->timestamps();
});
}
PHP實例執(zhí)行遷移:
PHP實例現(xiàn)在有了新的數(shù)據(jù)表了.
PHP實例假設(shè)我們需要添加一個新的字段,你可以回滾,然后修改遷移文件,再次執(zhí)行遷移,或者可以直接新建一個遷移文件
PHP實例查看新產(chǎn)生的遷移文件
PHP實例
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddExcerptToArticelsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
PHP實例只有空的 up 和 down 辦法.我們可以手工添加代碼,或者我們讓laravel為我們生成基礎(chǔ)代碼.刪除這個文件,重新生成遷移文件,注意添加參數(shù):
PHP實例現(xiàn)在,up 辦法里面有了初始代碼.
PHP實例
public function up()
{
Schema::table('articles', function(Blueprint $table)
{
//
});
}
PHP實例添加實際的數(shù)據(jù)修改代碼:
PHP實例
public function up()
{
Schema::table('articles', function(Blueprint $table)
{
$table->text('excerpt')->nullable();
});
}
public function down()
{
Schema::table('articles', function(Blueprint $table)
{
$table->dropColumn('excerpt');
});
}
PHP實例nullable() 表示字段也可以為空.
PHP實例再次執(zhí)行遷移并檢查數(shù)據(jù)庫.
PHP實例如果我們?yōu)榱撕猛?執(zhí)行回滾
PHP實例excerpt 列沒有了.
PHP實例以上所述就是本文的全部內(nèi)容了,希望能夠給大家熟練掌握Laravel5框架有所贊助.
歡迎參與《PHP實戰(zhàn):Laravel 5框架學(xué)習(xí)之?dāng)?shù)據(jù)庫遷移(Migrations)》討論,分享您的想法,維易PHP學(xué)院為您提供專業(yè)教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/11096.html