【调整】获取商品分类功能,从原先的只获取二级分类,改成递归获取无限级分类。

This commit is contained in:
jianweie code
2024-02-22 15:42:15 +08:00
parent 15d429a25b
commit 7ecbeb1373
2 changed files with 28 additions and 58 deletions

View File

@@ -109,46 +109,39 @@ namespace CoreCms.Net.Web.WebApi.Controllers
var jm = new WebApiCallBack() { status = true };
var data = await _goodsCategoryServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort, OrderByType.Asc, true, true);
var wxGoodCategoryDto = new List<WxGoodCategoryDto>();
var parents = data.Where(p => p.parentId == 0).ToList();
if (parents.Any())
{
parents.ForEach(p =>
{
var model = new WxGoodCategoryDto
{
id = p.id,
name = p.name,
imageUrl = !string.IsNullOrEmpty(p.imageUrl) ? p.imageUrl : "/static/images/common/empty.png",
sort = p.sort
};
var childs = data.Where(p => p.parentId == model.id).ToList();
if (childs.Any())
{
var childsList = new List<WxGoodCategoryChild>();
childs.ForEach(o =>
{
childsList.Add(new WxGoodCategoryChild()
{
id = o.id,
imageUrl = !string.IsNullOrEmpty(o.imageUrl) ? o.imageUrl : "/static/images/common/empty.png",
name = o.name,
sort = o.sort
});
});
model.child = childsList;
}
wxGoodCategoryDto.Add(model);
});
}
jm.status = true;
jm.data = wxGoodCategoryDto;
jm.data = GetCategories(data, 0);
return jm;
}
/// <summary>
/// 迭代方法
/// </summary>
/// <param name="oldCategories"></param>
/// <param name="parentId"></param>
/// <returns></returns>
private static List<WxGoodCategoryDto> GetCategories(List<CoreCmsGoodsCategory> oldCategories, int parentId)
{
List<WxGoodCategoryDto> childTree = new List<WxGoodCategoryDto>();
var model = oldCategories.Where(p => p.parentId == parentId).ToList();
foreach (var item in model)
{
var parentTree = new WxGoodCategoryDto();
parentTree.id = item.id;
parentTree.imageUrl = !string.IsNullOrEmpty(item.imageUrl) ? item.imageUrl : "/static/images/common/empty.png";
parentTree.name = item.name;
parentTree.sort = item.sort;
childTree.Add(parentTree);
parentTree.child = GetCategories(oldCategories, item.id);
}
return childTree;
}
#endregion
#region ============================================================