Category.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace app\common\model;
  3. use app\common\service\InstallService;
  4. use think\Model;
  5. use traits\model\SoftDelete;
  6. /**
  7. * 分类模型
  8. */
  9. class Category extends Model
  10. {
  11. use SoftDelete;
  12. // 开启自动写入时间戳字段
  13. protected $autoWriteTimestamp = 'int';
  14. // 定义时间戳字段名
  15. protected $createTime = 'createtime';
  16. protected $updateTime = 'updatetime';
  17. // 追加属性
  18. protected $append = [
  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. public function goods(){
  31. return $this->hasMany(Goods::class)->where('status',1);
  32. }
  33. /**
  34. * 读取分类类型
  35. * @return array
  36. */
  37. public static function getTypeList()
  38. {
  39. $typeList = config('site.categorytype');
  40. foreach ($typeList as $k => &$v) {
  41. $v = __($v);
  42. }
  43. return $typeList;
  44. }
  45. public function getTypeTextAttr($value, $data)
  46. {
  47. $value = $value ? $value : $data['type'];
  48. $list = $this->getTypeList();
  49. return isset($list[$value]) ? $list[$value] : '';
  50. }
  51. public function getFlagList()
  52. {
  53. return ['hot' => __('Hot'), 'index' => __('Index'), 'recommend' => __('Recommend')];
  54. }
  55. public function getFlagTextAttr($value, $data)
  56. {
  57. $value = $value ? $value : $data['flag'];
  58. $valueArr = explode(',', $value);
  59. $list = $this->getFlagList();
  60. return implode(',', array_intersect_key($list, array_flip($valueArr)));
  61. }
  62. /**
  63. * 读取分类列表
  64. * @param string $type 指定类型
  65. * @param string $status 指定状态
  66. * @return array
  67. */
  68. public static function getCategoryArray($type = null, $status = null,$with=[])
  69. {
  70. $list = collection(self::where(function ($query) use ($type, $status) {
  71. if (!is_null($type)) {
  72. $query->where('type', '=', $type);
  73. }
  74. if (!is_null($status)) {
  75. $query->where('status', '=', $status);
  76. }
  77. })->order('weigh', 'desc')->with($with)->select())->toArray();
  78. foreach ($list as $k=>$v){
  79. if(!empty($v['goods'])){
  80. foreach ($v['goods'] as $ko=>$goods){
  81. $list[$k]['goods'][$ko]['sku'] = GoodsSku::where('goods_id',$goods['id'])->field('id,name')->select();
  82. }
  83. }
  84. }
  85. return $list;
  86. }
  87. public static function mall($with=[]){
  88. return self::getCategoryArray('mall','normal',$with);
  89. }
  90. }