導(dǎo)語
做開發(fā)的時候,添加測試數(shù)據(jù)是必不可少的,laravel 內(nèi)置了很方便的數(shù)據(jù)填充,下面是實例。
注意:laravel5框架中已經(jīng)內(nèi)置了faker組建,不用安裝
數(shù)據(jù)遷移
先創(chuàng)建數(shù)據(jù)模型和數(shù)據(jù)遷移 php artisan make:model Models/FakerUser -m;
只創(chuàng)建幾個簡單字段,編輯 database/migrations/{now_date}_create_faker_users_table.php 文件
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('faker_users', function (Blueprint $table) {
$table->increments('id');
$table->char('name', 20)->comment('姓名');
$table->string('email', 50)->comment('郵箱');
$table->tinyInteger('age')->comment('年齡');
$table->char('city', 20)->comment('城市');
$table->timestamps();
});
DB::statement("ALTER TABLE `faker_users` comment'測試用戶表'"); // 表注釋
}
運行數(shù)據(jù)遷移 php artisan migrate
之后數(shù)據(jù)表創(chuàng)建完成。
數(shù)據(jù)填充
- 創(chuàng)建數(shù)據(jù)填充文件
php artisan make:seeder FakerUsersSeeder;
- 創(chuàng)建完成后,我們可以在
run()
方法中手動添加幾條測試數(shù)據(jù)。但是好的辦法,是使用模型工廠,接下來把注意力轉(zhuǎn)移到模型工廠中;
- 創(chuàng)建模型工廠
php artisan make:factory FakerUsersFactory;
- 在模型工廠中,可以通過 Faker\Generator 來生成測試數(shù)據(jù),編輯 database/factories/FakerUsersFactory.php
?php
use Faker\Generator as Faker;
$factory->define(\App\Models\FakerUser::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'age' => $faker->numberBetween(8, 80),// 數(shù)字在 8-80 之間隨機
'city' => $faker->city,
'created_at' => $faker->dateTimeBetween('-3 year', '-1 year'),// 時間在 三年到一年 之間
'updated_at' => $faker->dateTimeBetween('-1 year', '-5 month'),// 時間在 一年到五個月之間
];
});
由上述代碼可以很直白的看出 Faker\Generator 的作用。它可以生成的數(shù)據(jù)類型有很多,更多的類型可以看下官方文檔,雖然是英文的,不過都有示例,簡單易懂;
- Faker 生成的數(shù)據(jù)默認是英文,可以在 config/app.php 中將 faker_locale 設(shè)置為 zh_CN;
- 模型工廠寫好了,接下來就是調(diào)用。目光回到數(shù)據(jù)填充文件 database/seeds/FakerUsersSeeder.php,在
run()
方法中如下代碼
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(\App\Models\FakerUser::class)->times(1000)->make()->each(function ($model) {
// 數(shù)據(jù)入庫
$model->save();
});
}
time()
是生成的次數(shù),make()
方法是創(chuàng)建模型實例,在 each() 方法中將生成的模型實例入庫保存。
- 最后就是執(zhí)行數(shù)據(jù)填充,
composer dump-autoload
之后 php artisan db:seed --class=FakerUsersSeeder
測試
好了,看下數(shù)據(jù)庫的數(shù)據(jù)是否生成正確。看下總數(shù)
![](http://img.jbzj.com/file_images/article/201904/2019412102159011.png?201931210227)
總數(shù)沒有問題,隨機看十條數(shù)據(jù)
![](http://img.jbzj.com/file_images/article/201904/2019412102221845.png?2019312102228)
數(shù)據(jù)也是正確的。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
您可能感興趣的文章:- Laravel中數(shù)據(jù)遷移與數(shù)據(jù)填充的詳細步驟
- Laravel實現(xiàn)數(shù)據(jù)庫遷移與支持中文的填充
- Laravel框架使用Seeder實現(xiàn)自動填充數(shù)據(jù)功能