UpdateTopicUseCount.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/8/13
  6. * Time: 11:50
  7. */
  8. namespace App\Console\Commands;
  9. use App\Models\Post;
  10. use App\Models\Topic;
  11. use Illuminate\Console\Command;
  12. class UpdateTopicUseCount extends Command
  13. {
  14. /**
  15. * The name and signature of the console command.
  16. *
  17. * @var string
  18. */
  19. protected $signature = 'post:update_topic_use_count';
  20. /**
  21. * The console command description.
  22. *
  23. * @var string
  24. */
  25. protected $description = '更新话题使用数';
  26. /**
  27. * Create a new command instance.
  28. *
  29. * @return void
  30. */
  31. public function __construct(Post $post,
  32. Topic $topic)
  33. {
  34. parent::__construct();
  35. $this->post = $post;
  36. $this->topic = $topic;
  37. }
  38. /**
  39. * Execute the console command.
  40. *
  41. * @return mixed
  42. */
  43. public function handle()
  44. {
  45. $this->line("开始更新话题使用数");
  46. $topic = [];
  47. $bar = $this->output->createProgressBar($this->post->withTrashed()->count());
  48. $this->post->withTrashed()->chunk(100, function($posts) use ($bar, &$topic){
  49. foreach($posts as $post) {
  50. $topicIds = explode(',', $post->topic_ids);
  51. foreach($topicIds as $id){
  52. if(isset($topic[$id])){
  53. $topic[$id] += 1;
  54. }else{
  55. $topic[$id] = 1;
  56. }
  57. }
  58. $bar->advance();
  59. }
  60. usleep(100000);
  61. });
  62. foreach($topic as $id => $useCount){
  63. $this->topic->where('id', $id)->update(['use_count' => $useCount]);
  64. }
  65. $bar->finish();
  66. $this->line("\n更新话题使用数结束");
  67. }
  68. }