我尝试在 Node.js 应用程序中使用 Sequelize 创建订单,但在 Order.create() 方法和手动 INSERT INTO 查询方面都遇到问题。
这是我用来创建订单的代码:
let userId = 71;
let restaurantId = 43;
let status = 'submitted';
let items = '[{"itemName":"meal 1","itemDescription":"meal 1","itemPrice":2},
{"itemName":"drink 1","itemDescription":"drink 1","itemPrice":4},{"itemName":"drink
1","itemDescription":"drink 1","itemPrice":4}]'
let order = await Order.create({
customerId: userId,
restaurantId: restaurantId,
status: status,
items: items,
});
但是,这种方法不起作用,我没有收到明确的错误消息。我认为手动 SQL 查询可能有效,所以我尝试了以下方法:
const query = `
INSERT INTO orders (customerId, restaurantId, status, items)
VALUES (:customerId, :restaurantId, :status, :items);
`;
await sequelize.query(query, {
replacements: {
customerId: userId,
restaurantId: restaurantId,
status: status,
items: items,
},
type: QueryTypes.INSERT
});
这也不起作用,我没有看到任何结果。
有趣的是,当我直接在 MySQL Workbench 中运行以下手动查询时,它工作得很好:
INSERT INTO Orders (customerId, restaurantId, status, items)
VALUES (71, 43, 'submitted', '[{"itemName":"meal 1","itemDescription":"meal
1","itemPrice":2},{"itemName":"drink 1","itemDescription":"drink 1","itemPrice":4},
{"itemName":"drink 1","itemDescription":"drink 1","itemPrice":4}]');
这是我的订单模型,以防我缺少某些东西:
const Order = sequelize.define('Order', {
customerId:{
type: DataTypes.INTEGER,
allowNull: false,
references:{
model: 'Users',
key: 'id'
},
onDelete:'CASCADE',
onUpdate: 'CASCADE'
},
restaurantId:{
type: DataTypes.INTEGER,
allowNull: false,
references:{
model: 'Restaurants',
key: 'id'
},
onDelete:'CASCADE',
onUpdate: 'CASCADE'
},
status:{
type: DataTypes.STRING,
allowNull: false,
defaultValue: "pending"
},
items:{
type: DataTypes.JSON,
allowNull: false
},
}, { timestamps: true,
});
任何帮助或见解将不胜感激。预先感谢!
解决方案是删除
Orders
表并使用更新 Order
模型定义重新创建它,我已确保制作并运行迁移文件以防止这种情况发生,但似乎我错过了某个步骤,或者迁移文件只是出了问题。只需要重新创建 Orders
表!