FreeTemplate.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace common\models;
  3. use common\helpers\Cache;
  4. use Yii;
  5. /**
  6. * This is the model class for table "{{%FREE_TEMPLATE}}".
  7. *
  8. * @property string ID
  9. * @property string country_id 国家ID
  10. * @property double freight 运费
  11. * @property double free_shipping 免运费阈值
  12. * @property int created_at 创建时间
  13. * @property int updated_at 更新时间
  14. */
  15. class FreeTemplate extends \common\components\ActiveRecord
  16. {
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public static function tableName()
  21. {
  22. return '{{%FREE_TEMPLATE}}';
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function rules()
  28. {
  29. return [
  30. [['country_id', 'freight', 'free_shipping'], 'required'],
  31. [['freight', 'free_shipping'], 'number'],
  32. [['country_id'], 'unique'],
  33. ];
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function attributeLabels()
  39. {
  40. return [
  41. 'ID' => 'ID',
  42. 'country_id' => '国家ID',
  43. 'freight' => '运费',
  44. 'free_shipping' => '免运费阈值',
  45. 'created_at' => '创建时间',
  46. 'updated_at' => '更新时间',
  47. ];
  48. }
  49. public function country()
  50. {
  51. return $this->hasOne(Countries::class, ['id' => 'country_id']);
  52. }
  53. /**
  54. * 从缓存获取信息
  55. * @return array|mixed|\yii\db\ActiveRecord[]
  56. */
  57. public static function getFromCache()
  58. {
  59. $data = Yii::$app->cache->get(Cache::FREE_TEMPLATE_KEY);
  60. if (!$data) {
  61. // 获取信息
  62. $data = self::getAllData();
  63. Yii::$app->cache->set(Cache::FREE_TEMPLATE_KEY, $data);
  64. }
  65. return $data;
  66. }
  67. /**
  68. * @return array|\yii\db\ActiveRecord[]
  69. */
  70. public static function getAllData()
  71. {
  72. return static::find()->indexBy('ID')->orderBy('ID ASC')->asArray()->all();
  73. }
  74. /**
  75. * 更新缓存
  76. * @return array|\yii\db\ActiveRecord[]
  77. */
  78. public static function updateToCache()
  79. {
  80. // 获取配置
  81. $data = self::getAllData();
  82. Yii::$app->cache->set(Cache::FREE_TEMPLATE_KEY, $data);
  83. return $data;
  84. }
  85. /**
  86. * 通过$countryId获取
  87. * @param string $countryId
  88. * @return array|null
  89. */
  90. public static function getByCountryId(string $countryId): ?array
  91. {
  92. return self::findOneAsArray('country_id=:country_id', [':country_id' => $countryId]);
  93. }
  94. public static function deleteOne(string $countryId): bool
  95. {
  96. return self::deleteAll('country_id=:country_id', [':country_id' => $countryId]);
  97. }
  98. }