Sequelize.js returns 关联的旧值 table
Sequelize.js returns old value for associated table
我正在尝试更新产品(产品 table)的状态。
每个产品都有一个statusId,为“1”或“2”。
每个产品的 statusId 的默认值为“1”,如果路由被访问一次(反之亦然),则应更改为“2”。
"statusId" 和 "status"{"id"} 应该始终相同。
当我访问路由时,数据库和“statusId”的状态发生了变化,但是“status”的HTTP响应与数据库中的实际值不同。
示例响应:
{
"id": 1,
"name": "Drone",
"barcode": "123456789",
"description": "A drone that can fly",
"image": "drone.jpg",
"createdAt": "2020-12-22T17:30:15.000Z",
"updatedAt": "2020-12-22T17:30:22.841Z",
"statusId": 2,
"status": {
"id": 1,
"name": "in",
"createdAt": "2020-12-22T17:30:15.000Z",
"updatedAt": "2020-12-22T17:30:15.000Z"
}
}
协会:
db.status.hasMany(db.product, {
foreignKey: {allowNull: false} ,
});
db.product.belongsTo(db.status, {
foreignKey: {allowNull: false}
});
路线:
app
.route('/api/product/status/:id')
.put([authJwt.verifyToken], controller.updateProductStatus);
控制器:
exports.updateProductStatus = (req, res) => {
// Get product with id and update status only
Product.findOne({
where: {
id: req.params.id
},
include: [
Status
]
})
.then(product => {
let newStatus = product.statusId === 1 ? 2 : 1;
product.update({
statusId: newStatus
})
.then(
res.status(200).send(product)
)
.catch(err => {
console.log("Error (Update product): " + err);
res.status(404).send(err);
})
})
.catch(err => {
console.log("Error (find old product): " + err);
res.status(404).send(err);
});
};
如何将我的代码更改为return“状态”的“id”的正确值?
提前致谢!
您应该像这样重新加载模型实例:
.then(
product.reload({ include: [Status]})
.then(res.status(200).send(product))
)
我正在尝试更新产品(产品 table)的状态。 每个产品都有一个statusId,为“1”或“2”。
每个产品的 statusId 的默认值为“1”,如果路由被访问一次(反之亦然),则应更改为“2”。
"statusId" 和 "status"{"id"} 应该始终相同。
当我访问路由时,数据库和“statusId”的状态发生了变化,但是“status”的HTTP响应与数据库中的实际值不同。
示例响应:
{
"id": 1,
"name": "Drone",
"barcode": "123456789",
"description": "A drone that can fly",
"image": "drone.jpg",
"createdAt": "2020-12-22T17:30:15.000Z",
"updatedAt": "2020-12-22T17:30:22.841Z",
"statusId": 2,
"status": {
"id": 1,
"name": "in",
"createdAt": "2020-12-22T17:30:15.000Z",
"updatedAt": "2020-12-22T17:30:15.000Z"
}
}
协会:
db.status.hasMany(db.product, {
foreignKey: {allowNull: false} ,
});
db.product.belongsTo(db.status, {
foreignKey: {allowNull: false}
});
路线:
app
.route('/api/product/status/:id')
.put([authJwt.verifyToken], controller.updateProductStatus);
控制器:
exports.updateProductStatus = (req, res) => {
// Get product with id and update status only
Product.findOne({
where: {
id: req.params.id
},
include: [
Status
]
})
.then(product => {
let newStatus = product.statusId === 1 ? 2 : 1;
product.update({
statusId: newStatus
})
.then(
res.status(200).send(product)
)
.catch(err => {
console.log("Error (Update product): " + err);
res.status(404).send(err);
})
})
.catch(err => {
console.log("Error (find old product): " + err);
res.status(404).send(err);
});
};
如何将我的代码更改为return“状态”的“id”的正确值?
提前致谢!
您应该像这样重新加载模型实例:
.then(
product.reload({ include: [Status]})
.then(res.status(200).send(product))
)