UsersPath.php 2.0 KB

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