TagModel.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Support\Facades\Redis;
  4. use App\Models\User\UserModel;
  5. /**
  6. * App\Models\TagModel
  7. *
  8. * @property int $id
  9. * @property string $name 名称
  10. * @property int|null $group 分组[1:我的标签;2:]
  11. * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TagModel newModelQuery()
  12. * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TagModel newQuery()
  13. * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TagModel query()
  14. * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TagModel whereGroup($value)
  15. * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TagModel whereId($value)
  16. * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\TagModel whereName($value)
  17. * @mixin \Eloquent
  18. */
  19. class TagModel extends Model
  20. {
  21. protected $table = 'kdgx_partner_charge_user_tag';
  22. /**
  23. * 获取用户的tag
  24. * @param UserModel $user
  25. * @return array|mixed
  26. */
  27. public function getAllTagByUser($user)
  28. {
  29. if ($json_tags = Redis::get("charge_user_tag_{$user->uid}")) {
  30. $tags = json_decode($json_tags, true);
  31. return $tags;
  32. } else {
  33. $datas = $this->get()->toArray();
  34. $result = array();
  35. $taged_1 = explode(',', $user->tag_1);
  36. $taged_2 = explode(',', $user->tag_2);
  37. $taged_3 = explode(',', $user->tag_3);
  38. $taged_4 = explode(',', $user->tag_4);
  39. foreach ($datas as $data) {
  40. if (!empty($data) && in_array($data['group'], [1, 2, 3, 4])) {
  41. $data['belong'] = 0;
  42. if (in_array($data['id'], ${"taged_{$data['group']}"})) {
  43. $data['belong'] = 1;
  44. }
  45. $result[$data['group']][$data['id']] = $data;
  46. }
  47. }
  48. Redis::set("charge_user_tag_{$user->uid}", json_encode($result));
  49. return $result;
  50. }
  51. }
  52. // 刷新用户标签缓存
  53. public function flushTagByUser(int $uid, array $data, $is_add = true)
  54. {
  55. if ($json_tags = Redis::get("charge_user_tag_{$uid}")) {
  56. $tags = json_decode($json_tags, true);
  57. if ($is_add) {
  58. $tags[$data['group']][$data['tag_id']]['belong'] = 1;
  59. } else {
  60. $tags[$data['group']][$data['tag_id']]['belong'] = 0;
  61. }
  62. Redis::set("charge_user_tag_{$uid}", json_encode($tags));
  63. return $tags;
  64. } else {
  65. $user = UserModel::findOrFail($uid);
  66. $tags = $this->getAllTagByUser($user);
  67. return $tags;
  68. }
  69. }
  70. }