商品编辑的回显
商品修改
編輯按鈕點擊事件
在商品詳情頁,每一個商品后面,都會有一個編輯按鈕:
點擊這個按鈕,就會打開一個商品編輯窗口,我們看下它所綁定的點擊事件:(在item/Goods.vue)
對應的方法:
可以看到這里發起了兩個請求,在查詢商品詳情和sku信息。
因為在商品列表頁面,只有spu的基本信息:id、標題、品牌、商品分類等。比較復雜的商品詳情(spuDetail)和sku信息都沒有,編輯頁面要回顯數據,就需要查詢這些內容。
因此,接下來我們就編寫后臺接口,提供查詢服務接口。
查詢SpuDetail接口
GoodsController
需要分析的內容:
-
請求方式:GET
-
請求路徑:/spu/detail/{id}
-
請求參數:id,應該是spu的id
-
返回結果:SpuDetail對象
GoodsService
/*** 根據spuId查詢spuDetail* @param spuId* @return*/ public SpuDetail querySpuDetailBySpuId(Long spuId) {return this.spuDetailMapper.selectByPrimaryKey(spuId); }查詢sku
分析
-
請求方式:Get
-
請求路徑:/sku/list
-
請求參數:id,應該是spu的id
-
返回結果:sku的集合
GoodsController
@GetMapping("sku/list") public ResponseEntity<List<Sku>> querySkusBySpuId(@RequestParam("id")Long spuId){List<Sku> skus = this.goodsService.querySkusBySpuId(spuId);if (CollectionUtils.isEmpty(skus)) {return ResponseEntity.notFound().build();}return ResponseEntity.ok(skus); }GoodsService
需要注意的是,為了頁面回顯方便,我們一并把sku的庫存stock也查詢出來
/*** 根據spuId查詢sku的集合* @param spuId* @return*/ public List<Sku> querySkusBySpuId(Long spuId) {Sku sku = new Sku();sku.setSpuId(spuId);List<Sku> skus = this.skuMapper.select(sku);skus.forEach(s -> {Stock stock = this.stockMapper.selectByPrimaryKey(s.getId());s.setStock(stock.getStock());});return skus; }頁面回顯
隨便點擊一個編輯按鈕,發現數據回顯完成:
頁面提交
這里的保存按鈕與新增其實是同一個,因此提交的邏輯也是一樣的,這里不再贅述。
隨便修改點數據,然后點擊保存,可以看到瀏覽器已經發出請求:
后臺實現
接下來,我們編寫后臺,實現修改商品接口。
GoodsController
-
請求方式:PUT
-
請求路徑:/
-
請求參數:Spu對象
-
返回結果:無
?
@PutMapping("goods") public ResponseEntity<Void> updateGoods(@RequestBody SpuBo spuBo){this.goodsService.updateGoods(spuBo);return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); }GoodsService
spu數據可以修改,但是SKU數據無法修改,因為有可能之前存在的SKU現在已經不存在了,或者以前的sku屬性都不存在了。比如以前內存有4G,現在沒了。
因此這里直接刪除以前的SKU,然后新增即可。
代碼:
@Transactional public void update(SpuBo spu) {// 查詢以前skuList<Sku> skus = this.querySkuBySpuId(spu.getId());// 如果以前存在,則刪除if(!CollectionUtils.isEmpty(skus)) {List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());// 刪除以前庫存Example example = new Example(Stock.class);example.createCriteria().andIn("skuId", ids);this.stockMapper.deleteByExample(example);// 刪除以前的skuSku record = new Sku();record.setSpuId(spu.getId());this.skuMapper.delete(record);}// 新增sku和庫存saveSkuAndStock(spuBo);// 更新spuspu.setLastUpdateTime(new Date());spu.setCreateTime(null);spu.setValid(null);spu.setSaleable(null);this.spuMapper.updateByPrimaryKeySelective(spu);// 更新spu詳情this.spuDetailMapper.updateByPrimaryKeySelective(spu.getSpuDetail()); }?
總結
- 上一篇: 商品新增后台代码
- 下一篇: elasticsearch客户端介绍