UserTag.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Models;
  3. use App\Models\Relations\BelongsToUserTrait;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. class UserTag extends Model
  7. {
  8. use BelongsToUserTrait;
  9. protected $table = 'user_tags';
  10. protected $fillable = ['user_id', 'tag_id','questions','articles','answers','supports'];
  11. /*用户标签统计*/
  12. public static function multiIncrement($user_id,$tags,$field=false){
  13. if(!$tags){
  14. return false;
  15. }
  16. foreach( $tags as $tag ){
  17. $userTag = self::firstOrCreate([
  18. 'user_id'=> $user_id,
  19. 'tag_id' => $tag->id
  20. ]);
  21. if($field){
  22. $userTag->increment($field);
  23. }
  24. }
  25. }
  26. /*初始化统计用户标签数据*/
  27. public static function figures(){
  28. $tags = Tag::all();
  29. $users = User::where('status','>',0)->get();
  30. $users->map(function($user) use($tags) {
  31. $tags->map(function($tag) use($user){
  32. $articleNum = $tag->articles()->where("user_id","=",$user->id)->count();
  33. $questions = $tag->questions()->where('status','>',0)->get();
  34. $questionNum = $answerNum = $supportNum = $adoptionNum = 0;
  35. foreach($questions as $question){
  36. $questionNum++;
  37. $answer = $question->answers()->where('user_id','=',$user->id)->first();
  38. if($answer){
  39. $answerNum++;
  40. $supportNum += $answer->supports;
  41. if( $answer->adopted_at ){
  42. $adoptionNum++;
  43. }
  44. }
  45. }
  46. self::updateOrCreate([
  47. 'user_id'=>$user->id,
  48. 'tag_id'=>$tag->id
  49. ],
  50. [
  51. 'user_id' => $user->id,
  52. 'tag_id' => $tag->id,
  53. 'questions'=> $questionNum,
  54. 'articles' => $articleNum,
  55. 'answers' => $answerNum,
  56. 'supports' => $supportNum,
  57. 'adoptions'=> $adoptionNum
  58. ]);
  59. });
  60. });
  61. }
  62. }