| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace app\common\model;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\ModelNotFoundException;
- use think\exception\DbException;
- use think\Model;
- class UserPathModel extends Model
- {
- protected $name = "user_path";
- /**
- * 创建网体
- * @param int $newUserID
- * @param int $parentID
- * @return void
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function createPath(int $newUserID, int $parentID)
- {
- if ($parentID == 0) {
- return;
- }
- $parentIDs = $this->getAllParentIDs($parentID); // 查询直接父级的所有上级
- array_unshift($parentIDs, $parentID); // 直接父级放开头
- // 循环插入
- foreach ($parentIDs as $k => $v) {
- $this->insert([
- 'user_id' => $newUserID,
- 'parent_id' => $v,
- 'distance' => $k + 1,
- ]);
- }
- }
- /**
- * 获取直属上级ID
- * @param int $uid
- * @param int $distance
- * @return int
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getParentID(int $uid, int $distance = 1): int
- {
- $path = $this->where(['user_id' => $uid, 'distance' => $distance])->field('parent_id')->find();
- if (!is_null($path)) {
- return $path['parent_id'];
- }
- return 0;
- }
- /**
- * 获取所有上级ID
- * @param int $uid
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getAllParentIDs(int $uid): array
- {
- $parentIDs = [];
- $paths = $this->where('user_id', $uid)->field('parent_id')->order('distance', 'asc')->select();
- if (!is_null($paths)) {
- foreach ($paths as $v) {
- $parentIDs[] = $v['parent_id'];
- }
- }
- return $parentIDs;
- }
- }
|