FreeTemplate.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 int freight 运费
  11. * @property int 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. Yii::$app->cache->delete(Cache::FREE_TEMPLATE_KEY);
  61. if (!$data) {
  62. // 获取信息
  63. $data = self::getAllData();
  64. Yii::$app->cache->set(Cache::FREE_TEMPLATE_KEY, $data);
  65. }
  66. return $data;
  67. }
  68. /**
  69. * @return array|\yii\db\ActiveRecord[]
  70. */
  71. public static function getAllData()
  72. {
  73. return static::find()->indexBy('ID')->orderBy('ID ASC')->asArray()->all();
  74. }
  75. /**
  76. * 更新缓存
  77. * @return array|\yii\db\ActiveRecord[]
  78. */
  79. public static function updateToCache()
  80. {
  81. // 获取配置
  82. $data = self::getAllData();
  83. Yii::$app->cache->set(Cache::FREE_TEMPLATE_KEY, $data);
  84. return $data;
  85. }
  86. /**
  87. * 通过$countryId获取
  88. * @param string $countryId
  89. * @return array|null
  90. */
  91. public static function getByCountryId(string $countryId): ?array
  92. {
  93. return self::findOneAsArray('country_id=:country_id', [':country_id' => $countryId]);
  94. }
  95. public static function deleteOne(string $countryId): bool
  96. {
  97. return self::deleteAll('country_id=:country_id', [':country_id' => $countryId]);
  98. }
  99. }