Category.php 2.8 KB

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