close

 

 

遷移 (Migration)

假設我要建立並管理一個名為"admin"的資料表, 在Laravel中使用 artisan命令的 make:migration 命令來建立遷移檔案

php artisan make:migration create_admin_table --create="admin"

執行完成後會在 app/database/migrations/ 目錄下建立一個含有時間戳的遷移檔 2017_05_24_083647_create_admin_table.php

 

接著要在默認的 up()方法中, 建立你想使用在這個資料表內的欄位

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

class CreateAdminTable extends Migration
{
    public function up()
    {
        Schema::create('admin', function (Blueprint $table) {
            $table->increments('id');
            $table->string('account');
            $table->string('password');
            $table->string('name');
            $table->string('email');
            $table->string('remember_token', 100)->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('admin');
    }
}

*如果這個資料表是用來記錄 admin、user 這類的登入資訊, 請記得新增"remember_token"欄位來記錄session資訊

 

接著執行

php artisan migrate

 

完成之後可在資料庫中看到"admin"這張資料表

接著便可以對這張資料表做填充資料的動作

 

填充 (Seeder)

先使用 Artisan 命令建立一份Seeder檔案

php artisan make:seeder AdminTableSeeder

執行完成後會在 app/database/seeds 下看到這份檔案, 檔案內默認只有一個方法 run()

開啟 AdminTableSeeder.php , 並在 run() 函式內建立想要填充的資料內容

    public function run()
    {
        DB::table('admin')->insert([
            'account' => str_random(5),
            'password' => Hash::make('password'),
            'name' => str_random(10),
            'email'    => str_random(10).'@mail.com',
            'modify_time'    => '2015-04-03 03:13:30',
            'ip' => '1.1.1.1',
        ]);
    }

 

然後開啟 app/database/seeds/DatabaseSeeder.php , 並在 run()函式中寫入

$this->call(AdminTableSeeder::class);

透過 $this->call() 調用各個不同的填充檔案

 

最後執行 Artisan 命令進行填充即可。

php artisan db:seed //填充所有資料表

php artisan db:seed --class=AdminTableSeeder //填充單一資料表

 

 

arrow
arrow

    CccKaAsS 發表在 痞客邦 留言(0) 人氣()