【问题标题】:Sequelize: Ordering inside associationSequelize:在关联中排序
【发布时间】: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 表中获取最新价格。

  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 - 除非这是问题所在?

【问题讨论】:

  • 请添加您的ProductProductPrice 模型定义

标签: sorting sequelize.js associations


【解决方案1】:

我认为你应该在包含之后使用 order,像这样

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' ] ] });

【讨论】:

  • 如果这行得通,那就太愚蠢了。尽管如此,查询没有变化。
  • 只需访问我给出的官方文档的链接,为了在关联模型上工作,您必须首先包含该关联..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 2018-07-30
相关资源
最近更新 更多