序列化:关联内的排序

时间:2019-05-13 00:56:56

标签: sorting sequelize.js associations

模型

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表中获取最新价格。

  1. 产品的相关退货价格(单个产品have many价格)的排序-在id上以降序排序以limit:1的形式获取最新价格。
  2. 然后按价格重新订购多个产品 我正在尝试查询最新价格,然后以升序或降序订购多个产品。

产生错误的代码

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

1 个答案:

答案 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' ] ] });
相关问题