Config.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Facades\Storage;
  6. class Config extends Model
  7. {
  8. const TYPE_INPUT = 'input';
  9. const TYPE_TEXTAREA = 'textarea';
  10. const TYPE_FILE = 'file';
  11. const TYPE_SINGLE_SELECT = 'single_select';
  12. const TYPE_MULTIPLE_SELECT = 'multiple_select';
  13. const TYPE_OTHER = 'other';
  14. public static $typeMap = [
  15. self::TYPE_INPUT => '文本',
  16. self::TYPE_TEXTAREA => '多行文本',
  17. self::TYPE_FILE => '文件',
  18. self::TYPE_SINGLE_SELECT => '单选',
  19. self::TYPE_MULTIPLE_SELECT => '多选',
  20. self::TYPE_OTHER => '其他',
  21. ];
  22. protected $fillable = [
  23. 'category_id', 'type', 'name', 'slug', 'desc', 'options', 'value', 'validation_rules',
  24. ];
  25. protected $casts = [
  26. 'category_id' => 'integer',
  27. 'options' => 'array',
  28. 'value' => 'array',
  29. ];
  30. public function getTypeTextAttribute()
  31. {
  32. return static::$typeMap[$this->type] ?? '';
  33. }
  34. public function category()
  35. {
  36. return $this->belongsTo(ConfigCategory::class);
  37. }
  38. /**
  39. * 通过配置分类标识,获取所有配置
  40. *
  41. * @param string $categorySlug
  42. * @param bool $onlyValues
  43. *
  44. * @return Config[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
  45. */
  46. public static function getByCategorySlug(string $categorySlug, bool $onlyValues = false)
  47. {
  48. $configs = static::whereHas('category', function (Builder $query) use ($categorySlug) {
  49. $query->where('slug', $categorySlug);
  50. })->get();
  51. if ($onlyValues) {
  52. return $configs->pluck('value', 'slug');
  53. } else {
  54. return $configs;
  55. }
  56. }
  57. /**
  58. * @param Config[]|\Illuminate\Database\Eloquent\Collection $configs
  59. * @param array $inputs slug => value 键值对
  60. *
  61. * @return Config[]|\Illuminate\Database\Eloquent\Collection
  62. */
  63. public static function updateValues($configs, $inputs)
  64. {
  65. $configs->each(function (Config $config) use ($inputs) {
  66. if (key_exists($config->slug, $inputs)) {
  67. $config->update(['value' => $inputs[$config->slug]]);
  68. }
  69. });
  70. return $configs->pluck('value', 'slug');
  71. }
  72. }