Category.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. if (!$row['weigh']) {
  23. $row->save(['weigh' => $row['id']]);
  24. }
  25. });
  26. }
  27. public function setFlagAttr($value, $data)
  28. {
  29. return is_array($value) ? implode(',', $value) : $value;
  30. }
  31. /**
  32. * 读取分类类型
  33. * @return array
  34. */
  35. public static function getTypeList()
  36. {
  37. $typeList = config('site.categorytype');
  38. foreach ($typeList as $k => &$v) {
  39. $v = __($v);
  40. }
  41. return $typeList;
  42. }
  43. public function getTypeTextAttr($value, $data)
  44. {
  45. $value = $value ? $value : $data['type'];
  46. $list = $this->getTypeList();
  47. return $list[$value] ?? '';
  48. }
  49. public function getFlagList()
  50. {
  51. return ['hot' => __('Hot'), 'index' => __('Index'), 'recommend' => __('Recommend')];
  52. }
  53. public function getFlagTextAttr($value, $data)
  54. {
  55. $value = $value ? $value : $data['flag'];
  56. $valueArr = explode(',', $value);
  57. $list = $this->getFlagList();
  58. return implode(',', array_intersect_key($list, array_flip($valueArr)));
  59. }
  60. /**
  61. * 读取分类列表
  62. * @param string $type 指定类型
  63. * @param string $status 指定状态
  64. * @return array
  65. */
  66. public static function getCategoryArray($type = null, $status = null)
  67. {
  68. $list = collection(self::where(function ($query) use ($type, $status) {
  69. if (!is_null($type)) {
  70. $query->where('type', '=', $type);
  71. }
  72. if (!is_null($status)) {
  73. $query->where('status', '=', $status);
  74. }
  75. })->order('weigh', 'desc')->select())->toArray();
  76. return $list;
  77. }
  78. }