TagArticle.php 1.9 KB

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