TagArticle.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\model;
  4. use think\facade\Db;
  5. use app\model\Base;
  6. use app\model\Tag;
  7. class TagArticle extends Base
  8. {
  9. protected $pk = 'id';
  10. protected $schema = [
  11. 'id' => "int", // 主键id
  12. "tid" => "int", // 标签id
  13. "aid" => "int", // 文章id
  14. "cid" => "int", // 栏目id
  15. ];
  16. protected $autoWriteTimestamp = false;
  17. public function article()
  18. {
  19. return $this->belongsTo('Article', 'aid')->bind(['title', 'titlepic', 'summary', 'hits', 'create_time', 'username']);
  20. }
  21. public function category()
  22. {
  23. return $this->belongsTo('Category', 'cid')->bind(['category_url' => 'url', 'category_name' => 'name']);
  24. }
  25. public static function queryList($tagid)
  26. {
  27. return self::with(['article', 'category'])->where('tid', $tagid)->order('aid DESC')->paginate();
  28. }
  29. public static function saveArticleTag(array $tags, int $aid, int $cid)
  30. {
  31. foreach ($tags as $tagname) {
  32. $tag = Tag::where('tagname', $tagname)->findOrEmpty();
  33. if ($tag->isEmpty()) {
  34. $tag->tagname = $tagname;
  35. }
  36. $tag->nums += 1;
  37. $tag->save();
  38. self::create([
  39. 'tid' => $tag->id,
  40. 'aid' => $aid,
  41. 'cid' => $cid
  42. ]);
  43. }
  44. }
  45. public static function delArticleTag(array $tags, int $aid)
  46. {
  47. foreach ($tags as $tagname) {
  48. $tag = Tag::where('tagname', $tagname)->findOrEmpty();
  49. if ($tag != null) {
  50. $tag->nums = $tag->nums - 1;
  51. $tag->nums = $tag->nums > 0 ? $tag->nums : 0;
  52. $tag->save();
  53. self::where(['aid'=>$aid, 'tid'=>$tag->id])->delete();
  54. }
  55. }
  56. }
  57. }