UserPathModel.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\common\model;
  3. use think\db\exception\DataNotFoundException;
  4. use think\db\exception\ModelNotFoundException;
  5. use think\exception\DbException;
  6. use think\Model;
  7. class UserPathModel extends Model
  8. {
  9. protected $name = "user_path";
  10. /**
  11. * 创建网体
  12. * @param int $newUserID
  13. * @param int $parentID
  14. * @return void
  15. * @throws DataNotFoundException
  16. * @throws DbException
  17. * @throws ModelNotFoundException
  18. */
  19. public function createPath(int $newUserID, int $parentID)
  20. {
  21. if ($parentID == 0) {
  22. return;
  23. }
  24. $parentIDs = $this->getAllParentIDs($parentID); // 查询直接父级的所有上级
  25. array_unshift($parentIDs, $parentID); // 直接父级放开头
  26. // 循环插入
  27. foreach ($parentIDs as $k => $v) {
  28. $this->insert([
  29. 'user_id' => $newUserID,
  30. 'parent_id' => $v,
  31. 'distance' => $k + 1,
  32. ]);
  33. }
  34. }
  35. /**
  36. * 获取直属上级ID
  37. * @param int $uid
  38. * @param int $distance
  39. * @return int
  40. * @throws DataNotFoundException
  41. * @throws DbException
  42. * @throws ModelNotFoundException
  43. */
  44. public function getParentID(int $uid, int $distance = 1): int
  45. {
  46. $path = $this->where(['user_id' => $uid, 'distance' => $distance])->field('parent_id')->find();
  47. if (!is_null($path)) {
  48. return $path['parent_id'];
  49. }
  50. return 0;
  51. }
  52. /**
  53. * 获取所有上级ID
  54. * @param int $uid
  55. * @return array
  56. * @throws DataNotFoundException
  57. * @throws DbException
  58. * @throws ModelNotFoundException
  59. */
  60. public function getAllParentIDs(int $uid): array
  61. {
  62. $parentIDs = [];
  63. $paths = $this->where('user_id', $uid)->field('parent_id')->order('distance', 'asc')->select();
  64. if (!is_null($paths)) {
  65. foreach ($paths as $v) {
  66. $parentIDs[] = $v['parent_id'];
  67. }
  68. }
  69. return $parentIDs;
  70. }
  71. }