一.需求分析
- 查询完商品信息后可以通过商品信息中Cid做为商品类目表的主键值进行查询
- 页面中最终数据的效果和TbItem只差一个属性所以可以通过组合的形式实现
type TbItemChild struct { TbItem CategoryName string}
- 整体架构使用分层实现,商品类目代码也属于商品模块中功能,所以在item文件夹下新建cat文件夹.在cat文件夹中编写类目的代码.
- 由于需要把商品类目查询的功能暴露给item包下,所以编写商品类目业务代码时函数名称首字母大写.
二. 代码实现
- 在item文件夹下新建cat文件夹
- 在cat中新建TbItemCat.go
package cat//商品类目type TbItemCat struct { Id int ParentId int Name string Status byte SortOrder int8 IsParent byte Created string Updated string}
- 在item/cat下新建TbItemCatDao.go实现根据主键查询
package catimport ( "commons" "fmt")func selByIdDao(id int) (t *TbItemCat){ rows,err:=commons.Dql("select * from tb_item_cat where id=?",id) if err!=nil{ fmt.Println(err) return nil } if rows.Next(){ t =new (TbItemCat) rows.Scan(&t.Id,&t.ParentId,&t.Name,&t.Status,&t.SortOrder,&t.IsParent,&t.Created,&t.Updated) } commons.CloseConn() return}
- 在item/cat下新建TbItemCatService.go,并把函数暴露
package cat//根据id查询类目func ShowCatByIdService(id int) *TbItemCat { return selByIdDao(id)}
//给页面使用,实现商品类目type TbItemChild struct { TbItem CategoryName string}
- 修改item/TbItemService.go中代码
package itemimport ( "commons" "item/cat")func showItemService(page,rows int) (e *commons.Datagrid){ ts:=selByPageDao(rows,page) if ts!=nil{ itemChildren :=make([]TbItemChild,0) for i:=0;i<len(ts);i++{ var itemChild TbItemChild itemChild.Id = ts[i].Id itemChild.Updated=ts[i].Updated itemChild.Created=ts[i].Created itemChild.Status=ts[i].Status itemChild.Barcode=ts[i].Barcode //itemChild.Cid=ts[i].Cid //itemChild.Image=ts[i].Image itemChild.Price=ts[i].Price itemChild.Num=ts[i].Num itemChild.SellPoint=ts[i].SellPoint itemChild.Title=ts[i].Title itemChild.CategoryName = cat.ShowCatByIdService(ts[i].Cid).Name itemChildren= append(itemChildren,itemChild) } e= new(commons.Datagrid) e.Rows=itemChildren e.Total=selCount() return } return nil}