CategoryService.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace app\common\service;
  3. use app\common\model\Category;
  4. use app\common\traits\ServiceTrait;
  5. use Exception;
  6. use fast\Tree;
  7. class CategoryService
  8. {
  9. use ServiceTrait;
  10. /** @var Category */
  11. public static $Model = Category::class;
  12. public static function getTreeArray($type = 'goods', $pid = 0)
  13. {
  14. $tree = Tree::instance();
  15. $list = self::$Model::where('type', $type)->order('weigh asc,id asc')->select();
  16. $tree->init(collection($list)->toArray(), 'pid');
  17. return self::transformTree($tree->getTreeArray(0));
  18. }
  19. public static function getOptions($type = 'goods', $pid = 0)
  20. {
  21. $list = self::$Model::where('type', $type)->where('status', 'normal')->order('weigh asc,id asc')->column('name', 'id');
  22. return $list;
  23. }
  24. public static function transformTree($data)
  25. {
  26. return array_map(function ($item) {
  27. $transformedItem = [
  28. 'groupId' => (string)$item['id'],
  29. 'thumbnail' => $item['image'] ?: 'https://cdn-we-retail.ym.tencent.com/miniapp/category/category-default.png',
  30. 'name' => $item['name']
  31. ];
  32. if (isset($item['childlist']) && is_array($item['childlist']) && count($item['childlist']) > 0) {
  33. $transformedItem['children'] = self::transformTree($item['childlist']);
  34. }
  35. return $transformedItem;
  36. }, $data);
  37. }
  38. }