新聞中心
這篇文章主要介紹了Laravel Seeder怎么生成百萬模擬數(shù)據(jù),具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

我們提供的服務(wù)有:成都做網(wǎng)站、成都網(wǎng)站建設(shè)、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、寧津ssl等。為上1000+企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的寧津網(wǎng)站制作公司
Laravel 集成了 Faker 庫,并提供了 Seeder 可以幫助我們輕松地生成模擬數(shù)據(jù)。
先書寫數(shù)據(jù)倉庫和數(shù)據(jù)填充代碼
數(shù)據(jù)倉庫代碼
use App\Models\Topic;use Faker\Generator as Faker;$factory->define(Topic::class, function (Faker $faker) {
$sentence = $faker->sentence();
// 隨機取一個月以內(nèi)的時間
$updated_at = $faker->dateTimeThisMonth();
// 傳參為生成最大時間不超過,因為創(chuàng)建時間永遠(yuǎn)比更改時間要早
$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 實例
$faker = app(Faker\Generator::class);
$topics = factory(Topic::class)
->times(1000)
->make()
->each(function ($topic, $index) use ($user_ids, $category_ids, $faker){
// 從用戶 ID 數(shù)組中隨機取出一個并賦值
$topic->user_id = $faker->randomElement($user_ids);
// 話題分類,同上
$topic->category_id = $faker->randomElement($category_ids);
});
// 將數(shù)據(jù)集合轉(zhuǎn)換為數(shù)組,并插入到數(shù)據(jù)庫中
Topic::insert($topics->toArray());
}}我們通過是 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)你這樣做之后,你會發(fā)現(xiàn)如下報錯
General error: 1390 Prepared statement contains too many placeholders
這個問題是因為 MySQL 默認(rèn)支持的占位符最多為 65535(2^16-1) 個,寫入數(shù)據(jù)為 m 列,n 行。m*n 必須小于 65535。
所以沒法一次性插入大量數(shù)據(jù),查了一下 php artisan db:seed 也沒有提供執(zhí)行次數(shù)的相關(guān)參數(shù)。
最后,決定使用 shell 腳本進(jìn)行解決。
for (( i = 0; i < 1000; i++ )); do /usr/local/bin/php artisan db:seed --class=TopicsTableSeederdone
等待片刻,你會發(fā)現(xiàn) 100w 數(shù)據(jù)已經(jīng)生成完畢!
PS:數(shù)據(jù)倉庫和數(shù)據(jù)填充代碼來自 larabbs
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Laravel Seeder怎么生成百萬模擬數(shù)據(jù)”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
網(wǎng)站名稱:LaravelSeeder怎么生成百萬模擬數(shù)據(jù)
網(wǎng)址分享:http://www.dlmjj.cn/article/ijejpd.html


咨詢
建站咨詢
