laravel資料庫遷移詳解

來源:互聯網
上載者:User

在以前我們進行資料庫資料測試的時候一般是手動的添加資料,比如在資料庫查詢器中使用sql語句進行資料插入。如果資料較少,那還是蠻輕鬆的,但是如果資料過大,那就很蛋疼了,即使你將sql語句複製下來。但是這一切,在laravel中都變的非常輕鬆。

本文執行個體針對laravel最新的5.3版本進行測試,如若在其它版本出現問題,請在評論區留言。 建立表

對於喜歡命令列的朋友來說,laravel的artisan命令簡直不能太方便了。

關於artisan的資訊,大家可以參考:

英文文檔:https://laravel.com/docs/5.3/artisan

中文文檔:https://laravel-china.org/docs/5.3/artisan 開始

命令:php artisan make:migration create_users_table

意思:建立一張名為users的表。

接著你便能在database/migrations這個目錄下找到與2014_10_12_000000_create_users_table.php這個類似的檔案。

和以前用php語句建立表一樣,我們可以在2014_10_12_000000_create_users_table.php這個檔案中寫上我們要建立表的欄位及約束條件。

<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateUsersTable extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('users', function (Blueprint $table) {            $table->increments('id');            $table->string('name');            $table->string('email')->unique();            $table->string('password');            $table->rememberToken();            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists('users');    }}

一個migration類包含兩個方法up和down。

up中主要包含建立表的具體內容。

down中和前者相反。

Schema::create接受兩個參數。第一個是你要建立表的表名;第二個是一個閉包(匿名函數),擷取用於定義新表的 Blueprint 對象。

更多有關Migration的介紹可以參考:https://laravel.com/docs/5.3/migrations#migration-structure 常見列名類型對照

命令 描述
$table->increments('id'); 資料庫主鍵自增 ID
$table->integer('votes'); 等同於資料庫中的 INTEGER 類型
$table->float('amount'); 等同於資料庫中的 FLOAT 類型
$table->char('name', 4); 等同於資料庫中的 CHAR 類型
$table->string('name', 100); 等同於資料庫中的 VARCHAR
$table->dateTime('created_at'); 等同於資料庫中的 DATETIME 類型
$table->enum('choices', ['foo','bar']); 等同於資料庫中的 ENUM 類型
$table->tinyInteger('numbers'); 等同於資料庫中的 TINYINT 類型
$table->timestamps(); 添加 created_at 和 updated_at 列

更多有關列名類型對照的介紹可以參考:https://laravel.com/docs/5.3/migrations#creating-columns 一些列名約束條件的寫法

Schema::table('users', function ($table) {    $table->integer('votes')->unsigned();    //無符號類型});
修改器 描述
->first() 將該列置為表中第一個列 (僅適用於 MySQL)
->after('column') 將該列置於另一個列之後 (僅適用於 MySQL)
->nullable() 允許該列的值為 NULL
->default($value) 指定列的預設值
->unsigned() 設定integer 列為 UNSIGNED
在資料庫中產生表

產生命令:php artisan migrate

復原命令:php artisan migrate:rollback 填充測試資料(重點) 方法一

讓我們修改 Laravel 安裝時內建的 DatabaseSeeder 類,添加一個資料庫插入語句到 run 方法:

在database/seeders目錄下我們可以找到DatabaseSeeder.php這個檔案

<?phpuse Illuminate\Database\Seeder;class DatabaseSeeder extends Seeder{    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        DB::table('users')->insert([            'name' => str_random(10),            'email' => str_random(10).'@gmail.com',            'password' => bcrypt('secret'),        ]);    }}

接著執行命令:php artisan db:seed

現在你可以去資料庫中查看,會發現新增了一條資料

這裡有一個問題,如果我們後期的表多了,那麼這樣單個填充器類就不會變得無比巨大。在laravel中提供了一個解決方案, 我們可以建立額外的填充器來專門針對一張表。

命令:php artisan make:seeder UserTableSeeder

意思:建立一張名為users的種子類或者理解為填充測試的類。UserTableSeeder這個名字可以任意取,但是要好分辨。所有架構產生的填充器都位於database/seeders目錄。

<?phpuse Illuminate\Database\Seeder;class UsersTableSeeder extends Seeder{    /**     * Run the database seeds.     *     * @return void     */    public function run()    {                DB::table('users')->insert([            'name' => str_random(10),            'email' => str_random(10).'@gmail.com',            'password' => bcrypt('secret'),        ]);    }}

在 DatabaseSeeder 類中,你可以使用 call 方法執行額外的填充類,使用 call 方法允許你將資料庫填充分解成多個檔案。

<?phpuse Illuminate\Database\Seeder;class DatabaseSeeder extends Seeder{    /**     * Run the database seeds.     *     * @return void     */    public function run()    {         $this->call(UsersTableSeeder::class);    }}

與前面步驟一樣,接著執行命令:php artisan db:seed

現在你可以去資料庫中查看,會發現新增了一條資料 方法二

方法一和我們以前用sql語句插入一條資料是一樣的效果,所以並沒有多大的提升。我們想追求的是一次性填充多條測試資料,那麼我們可以使用方法二。

手動指定每一個模型填充的屬性是很笨重累贅的,在laravel中取而代之的,我們可以使用模型工廠來方便的產生大量的資料庫記錄。

首先,查看模型工廠文檔來學習如何定義工廠,定義工廠後,可以使用協助函數 factory 來插入記錄到資料庫。 模型工廠

作為開始,我們看一下 database/factories/ModelFactory.php 檔案,該檔案包含了一個工廠定義:

<?php/** * 運行資料庫填充 * @return void */$factory->define(App\User::class, function (Faker\Generator $faker) {    static $password;    return [        'name' => $faker->name,        'email' => $faker->unique()->safeEmail,        'password' => $password ?: $password = bcrypt('secret'),        'remember_token' => str_random(10),    ];});

在閉包中,作為工廠定義,我們返回該模型上所有屬性預設測試值。該閉包接收PHP庫Faker執行個體,從而允許你方便地為測試產生多種類型的隨機資料。

這裡要注意Faker執行個體,可以參考https://github.com/fzaninotto/Faker

這個Faker執行個體提供了很多可用的隨機資料,比如我們要填充人名,使用$faker->name即可,它最後會產生如Prof. King Feil這樣的資料。這無疑是非常方便的,可以高度類比。

更多有關模型工廠的介紹可以參考:

英文文檔:https://laravel.com/docs/5.3/database-testing#model-factories

中文文檔:https://laravel-china.org/docs/5.3/database-testing#model-factories 使用協助函數factory

<?phpuse Illuminate\Database\Seeder;class UsersTableSeeder extends Seeder{    /**     * Run the database seeds.     *     * @return void     */    public function run()    {        factory(App\User::class, 50)->create(['password' => bcrypt('123456')]);    }}

其中factory接受兩個參數:一個是Eloquent模型;另一個是插入資料數量。上面run方法中的語句表示建立50個模型,並將其存到資料庫中。

接著讓我們回到DatabaseSeeder.php調用call方法用於產生測試資料。

執行命令:php artisan db:seed

現在你可以去資料庫中查看,會發現新增了50條資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.