gpt4 book ai didi

sequelize.js - 无法使虚拟字段在 Sequelize 中工作

转载 作者:行者123 更新时间:2023-12-03 22:22:53 28 4
gpt4 key购买 nike

我已经用尽了我在这里和其他地方能找到的一切。看起来其他人正在取得成功,但我所做的一切都不会让我看到任何虚拟领域。我已经尝试过作为字段和 getterMethods 都无济于事。我已确保在我的项目中安装了最新的 Sequelize 版本。

这是对象定义:

var Orderitem = sequelize.define("Orderitem", {
description: { type: DataTypes.STRING(80), allowNull: false },
quantity: { type: DataTypes.DECIMAL(9,2), allowNull: false, defaultValue: 0},
unitWeight: { type: DataTypes.DECIMAL(9,2), allowNull: false, defaultValue: 0},
price: { type: DataTypes.DECIMAL(9,2), allowNull: false, defaultValue: 0},

totalPrice: {
type: DataTypes.VIRTUAL(DataTypes.DECIMAL(9,2), ['price', 'quantity']),
get() {
//return this.getDataValue('unitWeight') * this.getDataValue('quantity');
return 195.99;
}
},
totalWeight: {
type: DataTypes.VIRTUAL(DataTypes.DECIMAL(9,2), ['unitWeight', 'quantity']),
get() {
//return this.getDataValue('unitWeight') * this.getDataValue('quantity');
return 45;
}
},
}, {
/*
getterMethods: {
testFoo: function () {
return 'Foo';
},
totalPrice: function () {
return this.getDataValue('price') * this.getDataValue('quantity');
},
totalWeight: function() {
return this.getDataValue('unitWeight') * this.getDataValue('quantity');
}
},
*/
classMethods: {
associate: function(models) {
Orderitem.belongsTo(models.Order, {onDelete: 'CASCADE'})
}
}

正如所引用的,它试图使用具有 VIRTUAL 类型的属性定义。我也试过只使用虚拟的,没有额外的类型或依赖项。为了测试,我还对样本返回值进行了硬编码。

使用 getterMethods(在此处注释)的替代方法也好不到哪里去。

根据我能找到的所有内容,我应该能够执行查找(findOne、findAll 等),并且这些应该与所有其他字段一起作为字段返回。前 4 个字段从数据库返回预期值。虚拟字段无处可寻。使用上述任一方法,我做错了什么?

检索代码为:
OrderController.items = function (orderId, callback) {
models.Orderitem.findAll({
//attributes: Object.keys(models.Orderitem.attributes).concat([ 'totalPrice','totalWeight']),
where: {orderId: orderId}, raw: true
}).then(function(orderitems) {
callback(null, orderitems)
}).catch(function(error) {
callback(error, null)
});
};

没有错误,项目按预期检索,一切正常*除了虚拟字段。他们根本就找不到。请求原始对象或完整对象没有区别。

最佳答案

虚拟以它定义的方式工作。

问题在于您检索结果的方式。通过在查询中使用 raw 选项,Sequelize 假定您不想创建 DAO,因此它不会评估虚拟对象,也不会自己创建实例。

OrderController.items = function (orderId, callback) {
models.Orderitem.findAll({
where: {orderId: orderId} // commenting out `raw: true`
}).then(function(orderitems) {
if ( orderitems.length > 0 ) {
console.log(orderitems[0].totalPrice);
};
callback(null, orderitems)
}).catch(function(error) {
callback(error, null)
});
};

您可以在 Sequelize Documentation 中阅读有关 raw 选项的更多信息。

关于sequelize.js - 无法使虚拟字段在 Sequelize 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40700301/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com