RewardPointSetting.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Longyi\RewardPoints\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. class RewardPointSetting extends Model
  5. {
  6. protected $table = 'mw_reward_points_settings';
  7. protected $fillable = [
  8. 'code',
  9. 'name',
  10. 'value',
  11. 'type',
  12. 'group',
  13. 'sort_order',
  14. 'options',
  15. 'description',
  16. 'is_enabled'
  17. ];
  18. protected $casts = [
  19. 'sort_order' => 'integer',
  20. 'is_enabled' => 'boolean',
  21. 'options' => 'array'
  22. ];
  23. /**
  24. * 获取配置值(自动转换类型)
  25. */
  26. public function getTypedValueAttribute()
  27. {
  28. switch ($this->type) {
  29. case 'boolean':
  30. return (bool) $this->value;
  31. case 'number':
  32. return (float) $this->value;
  33. case 'select':
  34. $options = $this->options ?? [];
  35. return $options[$this->value] ?? $this->value;
  36. default:
  37. return $this->value;
  38. }
  39. }
  40. /**
  41. * 按分组获取所有启用的配置
  42. */
  43. public static function getGroupSettings($group)
  44. {
  45. return self::where('group', $group)
  46. ->where('is_enabled', true)
  47. ->orderBy('sort_order')
  48. ->get()
  49. ->pluck('value', 'code')
  50. ->toArray();
  51. }
  52. /**
  53. * 获取单个配置值
  54. */
  55. public static function getValue($code, $default = null)
  56. {
  57. $setting = self::where('code', $code)->first();
  58. if (!$setting) {
  59. return $default;
  60. }
  61. return $setting->typed_value;
  62. }
  63. /**
  64. * 设置配置值
  65. */
  66. public static function setValue($code, $value)
  67. {
  68. return self::updateOrCreate(
  69. ['code' => $code],
  70. ['value' => $value]
  71. );
  72. }
  73. }