Category.php 2.6 KB

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