需求:商品的上架与下架
一:建表的时候,添加paranoid:true字段,使用Goods.sync({ force: true })建表,建完之后注释
然后执行 node src/model/goods.model.js, 将表重新创建一下,表中会多一个deletedAt字段,根据deletedAt是否有值来判断上架和下架
const { DataTypes } = require('sequelize')
const seq = require('../db/seq')
const Goods = seq.define(
'zd_goods',
{
goods_name: {
type: DataTypes.STRING,
allowNull: false,
comment: '商品名称',
},
goods_price: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false,
comment: '商品价格',
},
goods_num: {
type: DataTypes.INTEGER,
allowNull: false,
comment: '商品库存',
},
goods_img: {
type: DataTypes.STRING,
allowNull: false,
comment: '商品图片的url',
},
},
{
paranoid: true,
}
)
// Goods.sync({ force: true })
module.exports = Goods
接口添加off和on
router.post('/:id/off', auth, hadAdminPermission, remove)
router.post('/:id/on', auth, hadAdminPermission, restore)
async remove(ctx) {
const res = await removeGoods(ctx.params.id)
if (res) {
ctx.body = {
code: 0,
message: '下架商品成功',
result: '',
}
} else {
return ctx.app.emit('error', invalidGoodsID, ctx)
}
}
async restore(ctx) {
const res = await restoreGoods(ctx.params.id)
if (res) {
ctx.body = {
code: 0,
message: '上架商品成功',
result: '',
}
} else {
return ctx.app.emit('error', invalidGoodsID, ctx)
}
}
async removeGoods(id) {
const res = await Goods.destroy({ where: { id } })
return res > 0 ? true : false
}
async restoreGoods(id) {
const res = await Goods.restore({ where: { id } })
return res > 0 ? true : false
}