Category.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. /**
  5. * 分类模型
  6. */
  7. class Category extends BaseModel
  8. {
  9. // 表名
  10. protected $name = 'category';
  11. // 自动写入时间戳字段
  12. protected $autoWriteTimestamp = 'int';
  13. // 定义时间戳字段名
  14. protected $createTime = 'createtime';
  15. protected $updateTime = 'updatetime';
  16. protected int $is_status_search = 0;// 默认使用 status = 1 筛选
  17. protected int $is_delete_search = 0;// 默认使用 is_delete = 0 筛选
  18. /**
  19. * 默认查询字段
  20. *
  21. * @var array|string[]
  22. */
  23. public array $select = [
  24. '*'
  25. ];
  26. // 追加属性
  27. protected $append = [
  28. 'type_text',
  29. 'flag_text',
  30. ];
  31. protected static function init()
  32. {
  33. self::afterInsert(function ($row) {
  34. $row->save(['weigh' => $row['id']]);
  35. });
  36. }
  37. public function setFlagAttr($value, $data)
  38. {
  39. return is_array($value) ? implode(',', $value) : $value;
  40. }
  41. /**
  42. * 读取分类类型
  43. * @return array
  44. */
  45. public static function getTypeList()
  46. {
  47. $typeList = config('site.categorytype');
  48. foreach ($typeList as $k => &$v) {
  49. $v = __($v);
  50. }
  51. return $typeList;
  52. }
  53. public function getTypeTextAttr($value, $data)
  54. {
  55. $value = $value ? $value : $data['type'];
  56. $list = $this->getTypeList();
  57. return $list[$value] ?? '';
  58. }
  59. public function getFlagList()
  60. {
  61. return ['hot' => __('Hot'), 'index' => __('Index'), 'recommend' => __('Recommend')];
  62. }
  63. public function getFlagTextAttr($value, $data)
  64. {
  65. $value = $value ? $value : $data['flag'];
  66. $valueArr = explode(',', $value);
  67. $list = $this->getFlagList();
  68. return implode(',', array_intersect_key($list, array_flip($valueArr)));
  69. }
  70. /**
  71. * 读取分类列表
  72. * @param string $type 指定类型
  73. * @param string $status 指定状态
  74. * @return array
  75. */
  76. public static function getCategoryArray($type = null, $status = null)
  77. {
  78. $list = collection(self::where(function ($query) use ($type, $status) {
  79. if (!is_null($type)) {
  80. $query->where('type', '=', $type);
  81. }
  82. if (!is_null($status)) {
  83. $query->where('status', '=', $status);
  84. }
  85. })->order('weigh', 'desc')->select())->toArray();
  86. return $list;
  87. }
  88. }