所以我正在开发一个 laravel 应用程序,我正在尝试优化我的种子,以便它们运行得更快。
http://bensmith.io/speeding-up-laravel-seeders
本指南帮助了很多。据此,我应该通过执行大量插入来最小化 SQL 查询的数量,并将时间减少到原始播种时间的 10%,这很棒。
所以现在我正在做类似的事情:
$comments = [];
for ($i = 0; $i < 50; $i++) {
$bar->advance();
$comments[] = factory(Comment::class)->make([
'created_at' => Carbon\Carbon::now(),
'updated_at' => Carbon\Carbon::now(),
'comment_type_id' => $comment_types->shuffle()->first()->id,
'user_id' => $users->shuffle()->first()->id,
'commentable_id' => $documents->shuffle()->first()->id,
])->toArray();
}
Comment::insert($comments);
这就像一个魅力。它将查询简化为一个。
但后来我有其他播种机可以处理转储,它们更复杂:
$dump = file_get_contents(database_path('seeds/dumps/serverdump.txt'));
DB::table('server')->truncate();
DB::statement($dump);
$taxonomies = DB::table('server')->get();
foreach($taxonomies as $taxonomy){
$bar->advance();
$group = PatentClassGroup::create(['name' => $taxonomy->name]);
preg_match_all('/([a-zA-Z0-9]+)/', $taxonomy->classes, $classes);
foreach(array_pop($classes) as $key => $class){
$type = strlen($class) == 4 ? 'GROUP' : 'MAIN';
$inserted_taxonomies[] = PatentClassTaxonomy::where('name', $class)->get()->count()
? PatentClassTaxonomy::where('name', $class)->get()->first()
: PatentClassTaxonomy::create(['name' => $class, 'type' => $type]);
}
foreach($inserted_taxonomies as $inserted_taxonomy){
try{
$group->taxonomies()->attach($inserted_taxonomy->id);
}catch(\Exception $e){
//
}
}
}
因此,当我将分类法附加到组时,我使用本机雄辩的代码,因此很难进行记录和批量插入。是的,我也可以四处寻找一种批量插入的方法,但我的问题是我必须编写和优化所有种子以及这些种子的每个部分才能批量插入。
有没有一种方法,我可以在其中收听 laravel 在播种时尝试执行的数据库查询。我知道我可以做这样的事情:
DB::listen(function($query) {
//
});
但它仍然会被正确执行。我想做的是以某种方式在变量中捕获查询,将其添加到堆栈中,然后在种子即将结束时执行整个堆栈。或者介于两者之间,因为我可能需要一些种子的 ID。有什么好的解决方法?以及如何使用智能解决方案真正优化 laravel 中的种子?