【发布时间】:2023-03-16 22:30:01
【问题描述】:
模型
product.js
module.exports = function(sequelize, DataTypes) {
var Product = sequelize.define(
"Product",
{
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
title: {
type: DataTypes.STRING(80),
allowNull: true,
},
},
{
tableName: "product",
},
);
Product.associate = function(models) {
Product.hasMany(models.ProductPrice, { foreignKey: "product_id" });
};
return Product;
};
product-price.js
module.exports = function(sequelize, DataTypes) {
var ProductPrice = sequelize.define(
"ProductPrice",
{
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
},
product_id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
},
price: {
type: DataTypes.INTEGER(11),
allowNull: true,
}
},
{
tableName: "product_price",
},
);
ProductPrice.associate = function(models) {
ProductPrice.belongsTo(models.Product, { foreignKey: "product_id" });
};
return ProductPrice;
};
我正在尝试使用 两种 排序从ProductPrice 表中获取最新价格。
- 产品相关返回价格的排序(单个产品
have many价格) - 在id上按降序排序以获取最新价格,limit:1。 - 然后按价格重新订购多个产品 我正在尝试查询最近的价格,然后按升序或降序订购多个产品。
产生错误的代码
models.Product.findAndCountAll({
//THIS LINE PRODUCES ERROR
order: [[models.ProductPrice, "price", "DESC"]],
include: [
//BRINGS THE CORRECT LATEST PRICE
{ model: models.ProductPrice, order: [["id", "DESC"]], limit:1 },
]
})
.then(data=>{
res.json({data.rows})
}
错误
SequelizeDatabaseError:“订单”中的未知列“ProductPrices.price” 子句'
注意:忽略我正在使用findAndCountAll - 除非这是问题所在?
【问题讨论】:
-
请添加您的
Product和ProductPrice模型定义
标签: sorting sequelize.js associations