<?php

namespace App\Console\Commands;

use App\Good;
use App\Trace;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class GoodTraceCount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:good-trace-count';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新码的数量';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->line('开始执行');
        $t1 = microtime(true);
        $traces = Trace::select(DB::raw('count(*) as trace_count, gid'))->groupBy('gid')->get()->toArray();
        foreach ($traces as $trace) {
            Good::where('id', $trace['gid'])->update([
                'trace_count' => $trace['trace_count']
            ]);
        }
        $t2 = microtime(true);
        $time = round($t2 - $t1, 3) . '秒';
        $count = count($traces);
        $this->line("执行完毕,共更新{$count}条数据，耗时{$time}。");
    }
}
