City.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace common\models;
  3. use Yii;
  4. /**
  5. * This is the model class for table "{{%city}}".
  6. *
  7. * @property integer $id
  8. * @property string $name
  9. * @property integer $parent_id
  10. * @property integer $sort
  11. * @property integer $deep
  12. */
  13. class City extends \yii\db\ActiveRecord
  14. {
  15. /**
  16. * @inheritdoc
  17. */
  18. public static function tableName()
  19. {
  20. return '{{%city}}';
  21. }
  22. /**
  23. * @inheritdoc
  24. */
  25. public function rules()
  26. {
  27. return [
  28. [['parent_id', 'sort', 'deep'], 'integer'],
  29. [['name'], 'string', 'max' => 255],
  30. ];
  31. }
  32. /**
  33. * @inheritdoc
  34. */
  35. public function attributeLabels()
  36. {
  37. return [
  38. 'id' => 'ID',
  39. 'name' => '地区名',
  40. 'parent_id' => '父ID',
  41. 'sort' => '排序',
  42. 'deep' => '地区深度',
  43. ];
  44. }
  45. /**
  46. * 解析全地址( 北京 北京市 东城区)成省ID 市ID 区ID
  47. * @param string|array $fullArea
  48. * @return array
  49. */
  50. public static function parseFullArea($fullArea)
  51. {
  52. if (is_string($fullArea)) {
  53. $fullArea = explode(' ', $fullArea);
  54. }
  55. list($province, $city, $area) = $fullArea;
  56. return [
  57. self::getId($province),
  58. self::getId($city),
  59. self::getId($area)
  60. ];
  61. }
  62. /**
  63. * 把省市区ID生成全地址 北京 北京市 东城区
  64. * @param $province
  65. * @param $city
  66. * @param $area
  67. * @return string
  68. */
  69. public static function createFullArea($province, $city, $area)
  70. {
  71. return join(' ', [
  72. self::getName($province),
  73. self::getName($city),
  74. self::getName($area)
  75. ]);
  76. }
  77. public static function getId($name)
  78. {
  79. return self::find()->where(['name' => $name])->select('id')->scalar();
  80. }
  81. public static function getName($id)
  82. {
  83. return self::find()->where(['id' => $id])->select('name')->scalar();
  84. }
  85. public static function getChildren($id = null)
  86. {
  87. if (is_null($id)) {
  88. return [];
  89. }
  90. $area = Yii::$app->cache->get(['area', $id]);
  91. if ($area === false) {
  92. $area = self::find()->where(['parent_id' => $id])->select('name')->indexBy('id')->column();
  93. Yii::$app->cache->set(['area', $id], $area);
  94. }
  95. return $area;
  96. }
  97. }