Area.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Support\Facades\DB;
  6. class Area extends Model
  7. {
  8. protected $table = 'areas';
  9. protected $fillable = ['name', 'parent_id', 'grade'];
  10. /**
  11. *从缓存中加载所有数据
  12. * @return mixed
  13. */
  14. public static function loadFromCache(){
  15. $areas = Cache::rememberForever('all_area_data', function() {
  16. return DB::table('areas')->orderBy('id','ASC')->get();
  17. });
  18. return $areas;
  19. }
  20. /**
  21. * 获取所有省份信息
  22. * @return mixed 省份信息
  23. */
  24. public static function provinces()
  25. {
  26. $provinces = [];
  27. foreach(self::loadFromCache() as $area){
  28. if($area->parent_id == 0){
  29. array_push($provinces,$area);
  30. }
  31. }
  32. return $provinces;
  33. }
  34. /**
  35. * 获取省份所有城市信息
  36. * @param $province_id
  37. * @return mixed 城市信息
  38. */
  39. public static function cities($province_id)
  40. {
  41. $cities = [];
  42. foreach(self::loadFromCache() as $area){
  43. if($area->parent_id == $province_id){
  44. array_push($cities,$area);
  45. }
  46. }
  47. return $cities;
  48. }
  49. public static function getName($id)
  50. {
  51. foreach(self::loadFromCache() as $area){
  52. if($area->id == $id){
  53. return $area->name;
  54. }
  55. }
  56. return '';
  57. }
  58. }