Category.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. ];
  17. protected static function init()
  18. {
  19. self::afterInsert(function ($row) {
  20. $row->save(['weigh' => $row['id']]);
  21. });
  22. }
  23. public function setFlagAttr($value, $data)
  24. {
  25. return is_array($value) ? implode(',', $value) : $value;
  26. }
  27. public function goods(){
  28. return $this->hasMany(Goods::class)->where('status',1);
  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,$with=[])
  66. {
  67. $list = collection(self::where(function ($query) use ($type, $status) {
  68. if (!is_null($type)) {
  69. $query->where('type', '=', $type);
  70. }
  71. if (!is_null($status)) {
  72. $query->where('status', '=', $status);
  73. }
  74. })->order('weigh', 'desc')->with($with)->select())->toArray();
  75. return $list;
  76. }
  77. public static function mall($with=[]){
  78. return self::getCategoryArray('mall','normal',$with);
  79. }
  80. }