City.php 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. <?php namespace App\Models;
  2. use Illuminate\Database\Eloquent\Factories\HasFactory;
  3. use Illuminate\Database\Eloquent\Model;
  4. use App\Models\Traits\Custom\Login;
  5. /**
  6. * 城市模型
  7. *
  8. */
  9. class City extends Model
  10. {
  11. use HasFactory,Login;
  12. // 与模型关联的表名
  13. protected $table = 'city';
  14. // 是否主动维护时间戳
  15. public $timestamps = false;
  16. // 定义时间戳字段名
  17. // const CREATED_AT = 'insert_time';
  18. // const UPDATED_AT = 'update_time';
  19. /**
  20. * 添加数据
  21. *
  22. */
  23. public function add($data)
  24. {
  25. // 时间
  26. $data['insert_time'] = time();
  27. $data['update_time'] = time();
  28. // 写入数据表
  29. $id = $this->query()->insertGetId($data);
  30. // 失败返回0
  31. if( !$id ) return 0;
  32. // 返回结果
  33. return $id;
  34. }
  35. /**
  36. * 添加数据
  37. *
  38. */
  39. public function edit($id,$data)
  40. {
  41. // 更新时间
  42. $data['update_time'] = time();
  43. // 写入数据表
  44. $result = $this->query()->where([['id','=',$id]])->update($data);
  45. // 失败返回0
  46. if( !$result ) return 0;
  47. // 返回结果
  48. return $id;
  49. }
  50. /**
  51. * 获取列表
  52. * @param Bool $force 是否强制更新
  53. *
  54. */
  55. public function getList($force = false)
  56. {
  57. // 结果数据
  58. $list = $force ? [] : cache('admin:city:list');
  59. // 不存在数据
  60. if ( !$list ) {
  61. // 从数据库获取数据
  62. $data = $this->query()->where([['status','=',0]])->get(['id','name','pid']);
  63. // 是否有数据
  64. $data = $data ? $data->toArray() : [];
  65. // 循环处理数据
  66. $list = [];
  67. // 进行更新
  68. foreach ($data as $value) {
  69. // 重组数据
  70. $list[$value['id']] = $value;
  71. }
  72. // 存起来
  73. cache(['admin:city:list'=>$list]);
  74. }
  75. // 返回结果
  76. return $list;
  77. }
  78. /**
  79. * 获取某个
  80. *
  81. * @param int $id ID
  82. * @param string $field 指定字段
  83. *
  84. */
  85. public function getOne($id,$field='')
  86. {
  87. // 获取列表数据
  88. $list = $this->getList();
  89. // 获取数据
  90. $one = isset($list[$id]) ? $list[$id] : [];
  91. // 返回值
  92. return empty($field) ? $one : ( isset($one[$field]) ? $one[$field] : null);
  93. }
  94. /**
  95. * 获取城市对应的ID
  96. *
  97. * @param string $name 城市名
  98. *
  99. */
  100. public function getIdByName($name){
  101. // 返回结果
  102. return (int) $this->query()->where([['name','=',$name]])->value('id');
  103. }
  104. /**
  105. * 获取城市列表
  106. *
  107. */
  108. public function getCityList(){
  109. // 城市json
  110. $cityList = @file_get_contents(resource_path('./js/').'city.json');
  111. // 解码
  112. $cityList = (array) json_decode($cityList,true);
  113. // 返回结果
  114. return $cityList;
  115. }
  116. }