Category.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. /**
  28. * 读取分类类型
  29. * @return array
  30. */
  31. public static function getTypeList()
  32. {
  33. $typeList = config('site.categorytype');
  34. foreach ($typeList as $k => &$v) {
  35. $v = __($v);
  36. }
  37. return $typeList;
  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 ['hot' => __('Hot'), 'index' => __('Index'), 'recommend' => __('Recommend')];
  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. }