Taggable.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Support\Facades\DB;
  6. class Taggable extends Model
  7. {
  8. protected $table = 'taggables';
  9. protected $fillable = ['source_type', 'source_id', 'tag_id'];
  10. public $timestamps = false;
  11. public static function hottest($type='all',$pageSize=20)
  12. {
  13. $tagIds = Tag::pluck('id');
  14. $query = DB::table('taggables')->select('tag_id',DB::raw('COUNT(id) as total_num'))
  15. ->whereIn('tag_id',$tagIds);
  16. if($type=='questions'){
  17. $query->where('taggable_type','=','App\Models\Question');
  18. }elseif($type=='articles'){
  19. $query->where('taggable_type','=','App\Models\Article');
  20. }
  21. $taggables = $query->groupBy('tag_id')
  22. ->orderBy('total_num','desc')
  23. ->paginate($pageSize);
  24. return $taggables;
  25. }
  26. /*全局热门标签*/
  27. public static function globalHotTags( $type='all' )
  28. {
  29. return Cache::remember('hot_tags_'.$type,300,function() use($type){
  30. $tags = self::hottest($type,25);
  31. $tags->map(function($tag){
  32. $tagInfo = Tag::find($tag->tag_id);
  33. if(!$tagInfo){
  34. $tag->name = '';
  35. }else{
  36. $tag->name = $tagInfo->name;
  37. }
  38. });
  39. return $tags;
  40. });
  41. }
  42. }