下面由laravel教程欄目給大家介紹Laravel Seeder生成百萬(wàn)模擬數(shù)據(jù),希望對(duì)需要的朋友有所幫助!
Laravel 集成了 Faker 庫(kù),并提供了 Seeder 可以幫助我們輕松地生成模擬數(shù)據(jù)。
先書(shū)寫(xiě)數(shù)據(jù)倉(cāng)庫(kù)和數(shù)據(jù)填充代碼
數(shù)據(jù)倉(cāng)庫(kù)代碼
use AppModelsTopic;use FakerGenerator as Faker;$factory->define(Topic::class, function (Faker $faker) { $sentence = $faker->sentence(); // 隨機(jī)取一個(gè)月以內(nèi)的時(shí)間 $updated_at = $faker->dateTimeThisMonth(); // 傳參為生成最大時(shí)間不超過(guò),因?yàn)閯?chuàng)建時(shí)間永遠(yuǎn)比更改時(shí)間要早 $created_at = $faker->dateTimeThisMonth($updated_at); return [ 'title' => $sentence, 'body' => $faker->text(), 'excerpt' => $sentence, 'created_at' => $created_at, 'updated_at' => $updated_at, ];});
數(shù)據(jù)填充代碼
class TopicsTableSeeder extends Seeder{ /** * Run the database seeds. * * @return void */ public function run() { // 所有用戶ID數(shù)組,如:[1,2,3,4] $user_ids = User::all()->pluck('id')->toArray(); // 所有分類 ID 數(shù)組,如:[1,2,3,4] $category_ids = Category::all()->pluck('id')->toArray(); // 獲取 Faker 實(shí)例 $faker = app(FakerGenerator::class); $topics = factory(Topic::class) ->times(1000) ->make() ->each(function ($topic, $index) use ($user_ids, $category_ids, $faker){ // 從用戶 ID 數(shù)組中隨機(jī)取出一個(gè)并賦值 $topic->user_id = $faker->randomElement($user_ids); // 話題分類,同上 $topic->category_id = $faker->randomElement($category_ids); }); // 將數(shù)據(jù)集合轉(zhuǎn)換為數(shù)組,并插入到數(shù)據(jù)庫(kù)中 Topic::insert($topics->toArray()); }}
我們通過(guò)是 times() 設(shè)置了填充的次數(shù),執(zhí)行數(shù)據(jù)填充命令,可以將 1000 條數(shù)據(jù)填充至 topics 表中,這很方便。
php artisan db:seed --class=TopicsTableSeeder
如果我們想要插入 100w 條數(shù)據(jù),是不是把 times() 的參數(shù)改為 1000,000 就可以了?當(dāng)你這樣做之后,你會(huì)發(fā)現(xiàn)如下報(bào)錯(cuò)
General error: 1390 Prepared statement contains too many placeholders
這個(gè)問(wèn)題是因?yàn)?mysql 默認(rèn)支持的占位符最多為 65535(2^16-1) 個(gè),寫(xiě)入數(shù)據(jù)為 m 列,n 行。m*n 必須小于 65535。
所以沒(méi)法一次性插入大量數(shù)據(jù),查了一下 php artisan db:seed
也沒(méi)有提供執(zhí)行次數(shù)的相關(guān)參數(shù)。
最后,決定使用 shell 腳本進(jìn)行解決。
for (( i = 0; i < 1000; i++ )); do /usr/local/bin/php artisan db:seed --class=TopicsTableSeederdone
等待片刻,你會(huì)發(fā)現(xiàn) 100w 數(shù)據(jù)已經(jīng)生成完畢!
PS:數(shù)據(jù)倉(cāng)庫(kù)和數(shù)據(jù)填充代碼來(lái)自 larabbs
推薦:最新的五個(gè)Laravel視頻教程