在 Laravel 中为数据库设定种子时使用进度条

2022-08-30 17:31:24

我必须将相当多的数据播种到数据库中,并且我希望能够在发生这种情况时向用户显示进度条。我知道这是有文档记录的:

但是我遇到了问题,包括在我的播种机中。

<?php

use Illuminate\Database\Seeder;

class SubDivisionRangeSeeder extends Seeder
{
    public function run()
    {
        $this->output->createProgressBar(10);
        for ($i = 0; $i < 10; $i++) {
            sleep(1);
            $this->output->advance();
        }
        $this->output->finish();
    }
}

<?php

use Illuminate\Database\Seeder;

class SubDivisionRangeSeeder extends Seeder
{
    public function run()
    {
        $this->output->progressStart(10);
        for ($i = 0; $i < 10; $i++) {
            sleep(1);
            $this->output->progressAdvance();
        }
        $this->output->progressFinish();
    }
}

https://mattstauffer.co/blog/advanced-input-output-with-artisan-commands-tables-and-progress-bars-in-laravel-5.1 相比

有什么想法吗?


答案 1

您可以通过以下方式访问输出$this->command->getOutput()

public function run()
{
    $this->command->getOutput()->progressStart(10);
    for ($i = 0; $i < 10; $i++) {
        sleep(1);
        $this->command->getOutput()->progressAdvance();
    }
    $this->command->getOutput()->progressFinish();
}

答案 2

这是我的实现代码,

<?php

use Illuminate\Database\Seeder;

class MediaTypeTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $media_types = [
            ['name'=>'movie'],
            ['name'=>'channel'],
            ['name'=>'drama'],
            // ['name'=>'ebook'],
            // ['name'=>'shopping'],
            // ['name'=>'reseller'],
            // ['name'=>'broadcasting']
        ];
        $this->command->getOutput()->progressStart(count($media_types));
        App\Models\Backoffice\MediaType::query()->delete();
        foreach($media_types as $media_type){
            App\Models\Backoffice\MediaType::create($media_type);
            $this->command->getOutput()->progressAdvance();
        }
        $this->command->getOutput()->progressFinish();
    }
}

推荐