123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php
- namespace app\admin\model\unishop;
- use think\Cache;
- use think\Model;
- class Area extends Model
- {
-
- protected $connection = 'database';
-
- protected $name = 'unishop_area';
-
- public static function getNameById($id)
- {
- $region = self::getCacheAll();
- return $region[$id]['name'];
- }
-
- public static function getIdByName($name, $level = 0, $pid = 0)
- {
- return static::useGlobalScope(false)->where(compact('name', 'level', 'pid'))
- ->value('id') ?: static::add($name, $level, $pid);
- }
-
- private static function add($name, $level = 0, $pid = 0)
- {
- $model = new static;
- $model->save(compact('name', 'level', 'pid'));
- Cache::rm('area');
- return $model->getLastInsID();
- }
-
- public static function getCacheTree()
- {
- return self::regionCache()['tree'];
- }
-
- public static function getCacheAll()
- {
- return self::regionCache()['all'];
- }
-
- private static function regionCache()
- {
- if (!Cache::get('area')) {
-
- $all = $allData = self::useGlobalScope(false)->column('id, pid, name, level', 'id');
-
- $tree = [];
- foreach ($allData as $pKey => $province) {
- if ($province['level'] === 1) {
- $tree[$province['id']] = $province;
- unset($allData[$pKey]);
- foreach ($allData as $cKey => $city) {
- if ($city['level'] === 2 && $city['pid'] === $province['id']) {
- $tree[$province['id']]['city'][$city['id']] = $city;
- unset($allData[$cKey]);
- foreach ($allData as $rKey => $region) {
- if ($region['level'] === 3 && $region['pid'] === $city['id']) {
- $tree[$province['id']]['city'][$city['id']]['region'][$region['id']] = $region;
- unset($allData[$rKey]);
- }
- }
- }
- }
- }
- }
- Cache::set('area', compact('all', 'tree'));
- }
- return Cache::get('area');
- }
- }
|