## 第3節數據庫遷移與數據填充
在上一小節中,我們已經使用過了數據遷移工具(Migration),在這一小節中,我們自己定義一個遷移文件。
### 數據庫遷移
我們要創建一個 articles 的表,那么遷移的命令是:
~~~
php artisan make:migration create_articles_table
~~~
輸入這條命令后會在 `D:\wamp\www\newblog.com\database\migrations\` 目錄下,生成一個遷移文件`2017_04_21_061247_create_articles_table`
~~~
Administrator@STU-PC MINGW32 /d/wamp/www/newblog.com (auth)
$ php artisan make:migration create_articles_table
Created Migration: 2017_04_21_061247_create_articles_table
~~~
下面我們來查看這個文件:
~~~
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
~~~
一個遷移類會包含兩個方法:up 和 down。up 方法可為數據庫增加新的數據表、字段、或索引,而 down 方法則可簡單的反向運行 up 方法的操作。
更多相關知識可以查看手冊:<http://d.laravel-china.org/docs/5.2/migrations#generating-migrations>
運行這條命令:
~~~
php artisan migrate
~~~
這樣就生成了一個 `atricles` 表。

### 數據填充文件
表中還沒有任何數據,我們可以使用 數據填充: `artisan 生成 Seeder`。
運行下面的命令,生成 Seeder:
~~~
php artisan make:seeder ArticleSeeder
~~~
會自動生成一個文件:`D:\wamp\www\newblog.com\database\seeds\ArticleSeeder.php`
~~~
<?php
use Illuminate\Database\Seeder;
class ArticleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
}
}
~~~
如何編寫數據填充,可以查看這里:<http://d.laravel-china.org/docs/5.2/seeding#writing-seeders>
### Article 模型
我們要使用 Eloquent ORM 模型去操作數據庫,大家可以通過這個鏈接了解:<http://d.laravel-china.org/docs/5.2/eloquent>
創建 Article Model 輸入下面的命令:
~~~
php artisan make:model models/Article
~~~
生成的 Atricle 類在:`D:\wamp\www\newblog.com\app\models\Article.php`
~~~
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
//
}
~~~
到這里,我們再來完善 Seeder 數據填充的編寫:
~~~
public function run()
{
DB::table('articles')->delete();
for ($i=0; $i < 10; $i++) {
\App\Models\Article::create([
'title' => 'Title '.$i,
'body' => 'Body '.$i,
'user_id' => 1,
]);
}
}
~~~
接下來,把 ArticleSeeder 注冊到系統內。
修改 `D:\wamp\www\newblog.com\database\seeds\DatabaseSeeder.php`
~~~
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
$this->call(ArticleSeeder::class);
}
}
~~~
執行命令,即完成了數據的導入:
~~~
php artisan db:seed
~~~
此時,我們在`phpmyadmin`工具中查看:

被插入了10條數據!
### 提交更新到 github
這里的提交步驟和上一小節一樣,就不在重復。
我們把該分支合并到master主分支。
~~~
git status
git branch -a
git checkout master
git merge auth
git push
git branch -d auth
~~~
備注:使用 `git status` 查看當前工作區是否為空。
