Category.php 2.9 KB

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