CreateUserRelationJob.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Jobs;
  4. use App\Repositories\UserLevelRelationRepository;
  5. use App\Repositories\UserRepository;
  6. use Hyperf\AsyncQueue\Job;
  7. class CreateUserRelationJob extends Job
  8. {
  9. public $params;
  10. private $relationRepo;
  11. private $userRepo;
  12. public function __construct($params)
  13. {
  14. // 这里最好是普通数据,不要使用携带 IO 的对象,比如 PDO 对象
  15. $this->params = $params;
  16. }
  17. /**
  18. * 生成用户裂变等级关系
  19. *
  20. * @return string|void
  21. */
  22. public function handle()
  23. {
  24. try {
  25. $this->makRepo();
  26. $level = 1;
  27. //一级
  28. $res = $this->relationRepo->create(['relation_uid' => $this->params['invite_id'], 'uid' => $this->params['invited_id'], 'relation_level' => $level]);
  29. if (!$res) {
  30. logger('CreateUserRelationJob', [$this->params]);
  31. return '';
  32. }
  33. $this->generateSuperiorRelation($this->params, $level);
  34. } catch (\Exception $exception) {
  35. logger('CreateUserRelationJob', [$exception->getMessage()]);
  36. }
  37. }
  38. /**
  39. * make对象
  40. */
  41. private function makRepo()
  42. {
  43. $this->relationRepo = make(UserLevelRelationRepository::class);
  44. $this->userRepo = make(UserRepository::class);
  45. }
  46. /**
  47. * 递归生成用户关系等级(最多生成四级)
  48. *
  49. * @param $data
  50. * @param $level
  51. */
  52. private function generateSuperiorRelation($data, &$level)
  53. {
  54. if ($level < 4) {
  55. $userParentUid = $this->userRepo->findBy('code', $data['invite_id'], 'parent_uid');
  56. if (!empty($userParentUid['parent_uid'])) {
  57. $level++;
  58. $this->relationRepo->create(['relation_uid' => $userParentUid['parent_uid'], 'uid' => $data['invited_id'], 'relation_level' => $level]);
  59. $data['invite_id'] = $userParentUid['parent_uid'];
  60. $this->generateSuperiorRelation($data, $level);
  61. }
  62. }
  63. }
  64. }