StoreCategory.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace app\models\store;
  3. use crmeb\basic\BaseModel;
  4. use think\facade\Cache;
  5. /**
  6. * TODO 产品分类Model
  7. * Class StoreCategory
  8. * @package app\models\store
  9. */
  10. class StoreCategory extends BaseModel
  11. {
  12. /**
  13. * 数据表主键
  14. * @var string
  15. */
  16. protected $pk = 'id';
  17. /**
  18. * 模型名称
  19. * @var string
  20. */
  21. protected $name = 'store_category';
  22. public static function pidByCategory($pid, $field = '*', $limit = 0)
  23. {
  24. $model = self::where('pid', $pid)->where('is_show', 1)->order('sort desc,id desc')->field($field);
  25. if ($limit) $model->limit($limit);
  26. return $model->select();
  27. }
  28. public static function pidBySidList($pid)
  29. {
  30. return self::where('pid', $pid)->field('id,cate_name,pid')->select();
  31. }
  32. public static function cateIdByPid($cateId)
  33. {
  34. return self::where('id', $cateId)->value('pid');
  35. }
  36. /*
  37. * 获取一级和二级分类
  38. * @return array
  39. * */
  40. public static function getProductCategory($expire = 800)
  41. {
  42. if (Cache::has('parent_category')) {
  43. return Cache::get('parent_category');
  44. } else {
  45. $parentCategory = self::pidByCategory(0, 'id,cate_name')->toArray();
  46. foreach ($parentCategory as $k => $category) {
  47. $category['child'] = self::pidByCategory($category['id'], 'id,cate_name,pic')->toArray();
  48. $parentCategory[$k] = $category;
  49. }
  50. Cache::set('parent_category', $parentCategory, $expire);
  51. return $parentCategory;
  52. }
  53. }
  54. /**
  55. * TODO 获取首页展示的二级分类 排序默认降序
  56. * @param string $field
  57. * @param int $limit
  58. * @return false|\PDOStatement|string|\think\Collection
  59. * @throws \think\db\exception\DataNotFoundException
  60. * @throws \think\db\exception\ModelNotFoundException
  61. * @throws \think\exception\DbException
  62. */
  63. public static function byIndexList($limit = 4, bool $bool = true, $field = 'id,cate_name,pid,pic')
  64. {
  65. if (!$limit && !$bool) return [];
  66. return self::where('pid', '>', 0)->where('is_show', 1)->field($field)->order('sort DESC')->limit($limit)->select();
  67. }
  68. /**
  69. * 获取子集分类查询条件
  70. * @return \think\model\relation\HasMany
  71. */
  72. public function children()
  73. {
  74. return $this->hasMany(self::class, 'pid', 'id')->where('is_show', 1)->order('sort DESC,id DESC');
  75. }
  76. }