Category.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. 'type_text',
  17. 'flag_text',
  18. ];
  19. protected static function init()
  20. {
  21. self::afterInsert(function ($row) {
  22. $row->save(['weigh' => $row['id']]);
  23. });
  24. }
  25. public function setFlagAttr($value, $data)
  26. {
  27. return is_array($value) ? implode(',', $value) : $value;
  28. }
  29. /**
  30. * 读取分类类型
  31. * @return array
  32. */
  33. public static function getTypeList()
  34. {
  35. $typeList = config('site.categorytype');
  36. foreach ($typeList as $k => &$v)
  37. {
  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)
  66. {
  67. $list = collection(self::where(function($query) use($type, $status) {
  68. if (!is_null($type))
  69. {
  70. $query->where('type', '=', $type);
  71. }
  72. if (!is_null($status))
  73. {
  74. $query->where('status', '=', $status);
  75. }
  76. })->order('weigh', 'desc')->select())->toArray();
  77. return $list;
  78. }
  79. }