Category.php 2.1 KB

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