TagArticleConsole.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\command;
  4. // 引入框架内置类
  5. use think\console\Input;
  6. use think\console\Output;
  7. use think\console\input\Argument;
  8. use think\console\Command;
  9. use think\facade\Db;
  10. use app\model\Tag;
  11. use app\model\Article;
  12. use app\model\TagArticle;
  13. class TagArticleConsole extends Command
  14. {
  15. protected function configure()
  16. {
  17. $this->setName('tagindex')
  18. ->addArgument('name', Argument::OPTIONAL, "console name")
  19. ->setDescription('Create a new tag index');
  20. }
  21. protected function execute(Input $input, Output $output)
  22. {
  23. $name = trim($input->getArgument('name'));
  24. $name = $name ?: 'thinkphp';
  25. $this->$name();
  26. }
  27. public function thinkphp()
  28. {
  29. echo "hello thinkphp";
  30. }
  31. public function makeTagArticleIndex()
  32. {
  33. // 查找所有keywords
  34. $keywordsList = Db::table("hu_article")->field('id,cid,keywords')->select();
  35. $i = $j = 0;
  36. foreach ($keywordsList as $value) {
  37. $id = $value['id'];
  38. $cid = $value['cid'];
  39. $keywords = $value['keywords'];
  40. $tags = explode(",",$keywords);
  41. foreach ($tags as $val) {
  42. $tagname = trim($val);
  43. if ($tagname) {
  44. $tag = Tag::where('tagname', $tagname)->findOrEmpty();
  45. if ($tag->isEmpty()) {
  46. $tag->tagname = $tagname;
  47. $tag->nums = 1;
  48. $tag->save();
  49. TagArticle::create([
  50. 'tid' => $tag->id,
  51. 'aid' => $id,
  52. 'cid' => $cid
  53. ]);
  54. $i++;
  55. $j++;
  56. } else {
  57. $tagArticle = TagArticle::where('aid', $id)->where('tid', $tag->id)->findOrEmpty();
  58. if ($tagArticle->isEmpty()) {
  59. $tagArticle->aid = $id;
  60. $tagArticle->cid = $cid;
  61. $tagArticle->tid = $tag->id;
  62. $tagArticle->save();
  63. $tag->nums += 1;
  64. $tag->save();
  65. $j++;
  66. }
  67. }
  68. }
  69. }
  70. }
  71. echo "新增标签:" . $i . "\n" . "新增标签关联文章" . $j . "\n";
  72. }
  73. }