Tag.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. namespace App\Models;
  3. use App\Models\Relations\BelongsToCategoryTrait;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\App;
  6. class Tag extends Model
  7. {
  8. use BelongsToCategoryTrait;
  9. protected $table = 'tags';
  10. protected $fillable = ['name', 'logo', 'description','category_id','followers'];
  11. public static function boot()
  12. {
  13. parent::boot();
  14. static::saved(function($tag){
  15. if(Setting()->get('xunsearch_open',0) == 1) {
  16. App::offsetGet('search')->update($tag);
  17. }
  18. });
  19. /*监听删除事件*/
  20. static::deleted(function($tag){
  21. /*删除关注*/
  22. Attention::where('source_type','=',get_class($tag))->where('source_id','=',$tag->id)->delete();
  23. $tag->userTags()->delete();
  24. /*删除用户标签*/
  25. UserTag::where('tag_id','=',$tag->id)->delete();
  26. if(Setting()->get('xunsearch_open',0) == 1){
  27. App::offsetGet('search')->delete($tag);
  28. }
  29. });
  30. }
  31. /**通过字符串添加标签
  32. * @param $tagString
  33. * @param $question_id
  34. */
  35. public static function multiSave($tagString,$taggable)
  36. {
  37. $tags = array_unique(explode(",",$tagString));
  38. /*删除所有标签关联*/
  39. if($tags){
  40. $taggable->tags()->detach();
  41. }
  42. foreach($tags as $tag_name){
  43. if(!trim($tag_name)){
  44. continue;
  45. }
  46. $tag = self::firstOrCreate(['name'=>$tag_name]);
  47. if(!$taggable->tags->contains($tag->id))
  48. {
  49. $taggable->tags()->attach($tag->id);
  50. }
  51. }
  52. return $tags;
  53. }
  54. /*搜索*/
  55. public static function search($word,$size=16)
  56. {
  57. $list = self::where('name','like',"$word%")->paginate($size);
  58. return $list;
  59. }
  60. public function questions()
  61. {
  62. return $this->morphedByMany('App\Models\Question', 'taggable');
  63. }
  64. public function articles()
  65. {
  66. return $this->morphedByMany('App\Models\Article', 'taggable');
  67. }
  68. public function followers()
  69. {
  70. return $this->morphToMany('App\Models\UserData', 'source','attentions','source_id','user_id');
  71. }
  72. public function userTags(){
  73. return $this->hasMany('App\Models\UserTag','tag_id');
  74. }
  75. /*相关标签检索*/
  76. public function relations($pageSize=25)
  77. {
  78. return self::where(function($query){
  79. $query->where('parent_id','=',$this->parent_id)
  80. ->where('id','<>',$this->id);
  81. })->orWhere('parent_id','=',$this->parent_id)
  82. ->orderBy('followers','desc')->take($pageSize)->get();
  83. }
  84. }