Category.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\common\model\sharing;
  3. use think\Cache;
  4. use app\common\model\BaseModel;
  5. /**
  6. * 拼团商品分类模型
  7. * Class Category
  8. * @package app\common\model\sharing
  9. */
  10. class Category extends BaseModel
  11. {
  12. protected $name = 'sharing_category';
  13. /**
  14. * 所有分类
  15. * @return mixed
  16. */
  17. public static function getALL()
  18. {
  19. $model = new static;
  20. if (!Cache::get('sharing_category_' . $model::$wxapp_id)) {
  21. $data = $model->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
  22. $all = !empty($data) ? $data->toArray() : [];
  23. $tree = [];
  24. foreach ($all as $first) {
  25. if ($first['parent_id'] != 0) continue;
  26. $twoTree = [];
  27. foreach ($all as $two) {
  28. if ($two['parent_id'] != $first['category_id']) continue;
  29. $threeTree = [];
  30. foreach ($all as $three)
  31. $three['parent_id'] == $two['category_id']
  32. && $threeTree[$three['category_id']] = $three;
  33. !empty($threeTree) && $two['child'] = $threeTree;
  34. $twoTree[$two['category_id']] = $two;
  35. }
  36. if (!empty($twoTree)) {
  37. array_multisort(array_column($twoTree, 'sort'), SORT_ASC, $twoTree);
  38. $first['child'] = $twoTree;
  39. }
  40. $tree[$first['category_id']] = $first;
  41. }
  42. Cache::tag('cache')->set('sharing_category_' . $model::$wxapp_id, compact('all', 'tree'));
  43. }
  44. return Cache::get('sharing_category_' . $model::$wxapp_id);
  45. }
  46. /**
  47. * 获取所有分类
  48. * @return mixed
  49. */
  50. public static function getCacheAll()
  51. {
  52. return self::getALL()['all'];
  53. }
  54. /**
  55. * 获取所有分类(树状结构)
  56. * @return mixed
  57. */
  58. public static function getCacheTree()
  59. {
  60. return self::getALL()['tree'];
  61. }
  62. /**
  63. * 获取所有分类(树状结构)
  64. * @return string
  65. */
  66. public static function getCacheTreeJson()
  67. {
  68. return json_encode(static::getCacheTree());
  69. }
  70. /**
  71. * 获取指定分类下的所有子分类id
  72. * @param $parent_id
  73. * @param array $all
  74. * @return array
  75. */
  76. public static function getSubCategoryId($parent_id, $all = [])
  77. {
  78. $arrIds = [$parent_id];
  79. empty($all) && $all = self::getCacheAll();
  80. foreach ($all as $key => $item) {
  81. if ($item['parent_id'] == $parent_id) {
  82. unset($all[$key]);
  83. $subIds = self::getSubCategoryId($item['category_id'], $all);
  84. !empty($subIds) && $arrIds = array_merge($arrIds, $subIds);
  85. }
  86. }
  87. return $arrIds;
  88. }
  89. }