一.需求分析
- 商品描述表(tb_item_desc)和商品表(tb_item)具有主外键关系,商品的主键也是商品描述的主键,使用工具函数生成的主键也当作商品描述表的主键
- 商品描述中信息来源于页面中KindEditor的富文本编辑框,里面带有HTML代码直接保存就可以
- 多表新增时要考虑事务的问题,本功能中使用最原始的方式实现(多个DML,多个事务,效率低),后面多表新增使用标准的事务方式,让同学们有对比,看看哪个方式较好.
- 只需要在DAO和Service中添加代码即可.
二.代码实现
- 在/item文件夹下新建desc文件夹,并在desc文件夹下新建TbItemDesc.go编写实体
package desc//商品描述type TbItemDesc struct { ItemId int ItemDesc string Created string Updated string}
- 在/item/desc下新建TbItemDescDao.go
package descimport ( "commons" "fmt")//新增描述func insertDescDao(t TbItemDesc ) int{ count,err:=commons.Dml("insert into tb_item_desc values(?,?,?,?)",t.ItemId,t.ItemDesc,t.Created,t.Updated) if err!=nil{ fmt.Println(err) return -1 } return int(count)}
- 在/item/desc下新建TbItemDescService.go,并把新增暴露给其他package
package desc//新增func Insert(t TbItemDesc) int{ return insertDescDao(t)}
- 在/item/TbItemDao.go中添加删除函数
//根据id删除func delById(id int) int{ count,err:=commons.Dml("delete from tb_item where id=?",id) if err!=nil{ fmt.Println(err) return -1 } return int(count)}
- 修改/item/TbItemService.go中新增商品业务代码
//商品新增func insetService(f url.Values) (e commons.EgoResult){ var t TbItem cid,_:=strconv.Atoi(f["Cid"][0]) t.Cid =cid t.Title = f["Title"][0] t.SellPoint = f["SellPoint"][0] price,_:=strconv.Atoi(f["Price"][0]) t.Price = price num,_:=strconv.Atoi(f["Num"][0]) t.Num=num t.Image = f["Image"][0] t.Status = 1 date:=time.Now().Format("2006-01-02 15:04:05") t.Created =date t.Updated = date id:=commons.GenId() t.Id = id //商品表新增执行 count :=insertItemDao(t) if count>0{ //商品描述新增 var tbItemDesc desc.TbItemDesc tbItemDesc.ItemId = id tbItemDesc.Created = date tbItemDesc.Updated = date tbItemDesc.ItemDesc = f["Desc"][0] countDesc:=desc.Insert(tbItemDesc) if countDesc>0{ e.Status = 200 }else{ //删除商品中数据 delById(id) e.Status = 400 } } return}