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; } }