UpdateTopicUseCount.php 1.9 KB

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