TagArticle.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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)->findOrEmpty();
  35. if ($tag->isEmpty()) {
  36. $tag->tagname = $tagname;
  37. }
  38. $tag->nums += 1;
  39. $tag->save();
  40. self::create([
  41. 'tid' => $tag->id,
  42. 'aid' => $aid,
  43. 'cid' => $cid
  44. ]);
  45. }
  46. }
  47. public static function delArticleTag(array $tags, int $aid)
  48. {
  49. foreach ($tags as $tagname) {
  50. $tag = Tag::where('tagname', $tagname)->findOrEmpty();
  51. if ($tag != null) {
  52. $tag->nums = $tag->nums - 1;
  53. $tag->nums = $tag->nums > 0 ? $tag->nums : 0;
  54. $tag->save();
  55. self::where(['aid'=>$aid, 'tid'=>$tag->id])->delete();
  56. }
  57. }
  58. }
  59. }