Citys.php 3.3 KB

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