Category.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace app\common\model;
  3. use app\common\service\InstallService;
  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. ];
  18. protected static function init()
  19. {
  20. self::afterInsert(function ($row) {
  21. $row->save(['weigh' => $row['id']]);
  22. });
  23. }
  24. public function setFlagAttr($value, $data)
  25. {
  26. return is_array($value) ? implode(',', $value) : $value;
  27. }
  28. public function goods(){
  29. return $this->hasMany(Goods::class)->where('status',1);
  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 isset($list[$value]) ? $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,$with=[])
  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')->with($with)->select())->toArray();
  76. foreach ($list as $k=>$v){
  77. if(!empty($v['goods'])){
  78. foreach ($v['goods'] as $ko=>$goods){
  79. $list[$k]['goods'][$ko]['sku'] = GoodsSku::where('goods_id',$goods['id'])->field('id,name')->select();
  80. }
  81. }
  82. }
  83. return $list;
  84. }
  85. public static function mall($with=[]){
  86. return self::getCategoryArray('mall','normal',$with);
  87. }
  88. }