RebuildKnowledgeStatsCommand.php 920 B

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\KnowledgePoint;
  4. use App\Models\QuestionKpRelation;
  5. use Illuminate\Console\Command;
  6. class RebuildKnowledgeStatsCommand extends Command
  7. {
  8. protected $signature = 'knowledge:rebuild-stats';
  9. protected $description = 'Recalculate knowledge stats from questions';
  10. public function handle(): int
  11. {
  12. $stats = QuestionKpRelation::query()
  13. ->selectRaw('kp_code, COUNT(*) as question_count')
  14. ->groupBy('kp_code')
  15. ->get();
  16. foreach ($stats as $row) {
  17. KnowledgePoint::query()
  18. ->where('kp_code', $row->kp_code)
  19. ->update([
  20. 'stats' => [
  21. 'question_count' => (int) $row->question_count,
  22. ],
  23. ]);
  24. }
  25. $this->info('Knowledge stats rebuilt.');
  26. return self::SUCCESS;
  27. }
  28. }