模型
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
?
答案 0 :(得分:0)
我认为您应该在包含之后使用订单,像这样
models.Product.findAndCountAll({
include: [
//BRINGS THE CORRECT LATEST PRICE
{ model: models.ProductPrice, order: [["id", "DESC"]], limit:1 },
]
//THIS LINE PRODUCES ERROR
order: [models.ProductPrice, "price", "DESC"],
})
.then(data=>{
res.json({data.rows})
}
有关更多参考,eagerly-loaded-models,
修改 从官方文档复制的行
Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] });