除了大量插入之外,如何优化 laravel 种子以加快播种速度/

Roh*_*han 5 php optimization laravel laravel-5 laravel-seeding

所以我正在开发一个 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);
Run Code Online (Sandbox Code Playgroud)

这就像一个魅力。它将查询缩减为单个查询。

但是我还有其他播种机来处理转储,它们更复杂:

$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){
            //
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当我将分类法附加到组时,我使用本机雄辩代码,因此记录和批量插入很困难。是的,我也可以摆弄并找出一种批量插入的方法,但我的问题是我必须编写和优化所有种子以及这些种子的每个部分以进行批量插入。

有没有办法让我可以监听 Laravel 在播种时尝试执行的数据库查询。我知道我可以做这样的事情:

DB::listen(function($query) {
    //
});
Run Code Online (Sandbox Code Playgroud)

但它仍然会被正确执行。我想做的是以某种方式捕获变量中的查询,将其添加到堆栈中,然后在种子即将结束时执行整个堆栈。或者也介于两者之间,因为我可能需要一些种子的 ID。有什么好的解决方法吗?如何使用智能解决方案真正优化 Laravel 中的种子?