Category.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. ];
  21. protected static function init()
  22. {
  23. self::afterInsert(function ($row) {
  24. $row->save(['weigh' => $row['id']]);
  25. });
  26. }
  27. public function setFlagAttr($value, $data)
  28. {
  29. return is_array($value) ? implode(',', $value) : $value;
  30. }
  31. /**
  32. * 读取分类类型
  33. * @return array
  34. */
  35. public static function getTypeList()
  36. {
  37. return ['product'=>__('Product')];
  38. }
  39. public function getTypeTextAttr($value, $data)
  40. {
  41. $value = $value ? $value : $data['type'];
  42. $list = $this->getTypeList();
  43. return isset($list[$value]) ? $list[$value] : '';
  44. }
  45. public function getFlagList()
  46. {
  47. return ['index' => __('Index')];
  48. }
  49. public function getFlagTextAttr($value, $data)
  50. {
  51. $value = $value ? $value : $data['flag'];
  52. $valueArr = explode(',', $value);
  53. $list = $this->getFlagList();
  54. return implode(',', array_intersect_key($list, array_flip($valueArr)));
  55. }
  56. /**
  57. * 读取分类列表
  58. * @param string $type 指定类型
  59. * @param string $status 指定状态
  60. * @return array
  61. */
  62. public static function getCategoryArray($type = null, $status = null)
  63. {
  64. $list = collection(self::where(function ($query) use ($type, $status) {
  65. if (!is_null($type)) {
  66. $query->where('type', '=', $type);
  67. }
  68. if (!is_null($status)) {
  69. $query->where('status', '=', $status);
  70. }
  71. })->order('weigh', 'desc')->select())->toArray();
  72. return $list;
  73. }
  74. /**
  75. * 关联上一级
  76. * @return \think\model\relation\HasOne
  77. */
  78. public function parent()
  79. {
  80. return $this->hasOne('category', 'id', 'pid');
  81. }
  82. }