Skip to content

Ordering inside association #10920

Open
Open

Description

@asgharmusani

What are you doing?

I'm trying to fetch the latest price from the ProductPrice table and ordering the products using "this" fetched price - involves two kinds of ordering.

  1. For Latest Price - The ordering of the associated returned prices of a product (single product have many prices) - Sorting in Descending order On id to get the latest price, with limit:1.
  2. Then re-ordering of the multiple products by price
    I am trying to query the most recent price and then order the multiple products whether in ascending or descending order.

Query

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})
      }

What is happening?

Error

SequelizeDatabaseError: Unknown column 'ProductPrices.price' in 'order clause'

Models

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;
};

What do you expect to happen?

Expected data.

// ordered by price + latest price
Products: [
  {
    id: 47,
    title: "Product #3",
    createdAt: "2019-02-19T09:35:02.000Z",
    updatedAt: "2019-02-19T09:35:02.000Z",
    ProductPrices: [
      {
        id: 1,
        product_id: 47,
        price: 15000,
        createdAt: "2019-02-19T09:35:02.000Z",
        updatedAt: "2019-02-19T09:35:02.000Z",
      },
    ],
  },
  {
    id: 73,
    title: "Product #7",
    createdAt: "2019-02-19T09:35:02.000Z",
    updatedAt: "2019-02-19T09:35:02.000Z",
    ProductPrices: [
      {
        id: 3,
        product_id: 47,
        price: 14000,
        createdAt: "2019-02-19T09:35:02.000Z",
        updatedAt: "2019-02-19T09:35:02.000Z",
      },
    ],
  },
  {
    id: 21,
    title: "Product #2",
    createdAt: "2019-02-19T09:35:02.000Z",
    updatedAt: "2019-02-19T09:35:02.000Z",
    ProductPrices: [
      {
        id: 2,
        product_id: 47,
        price: 13000,
        createdAt: "2019-02-19T09:35:02.000Z",
        updatedAt: "2019-02-19T09:35:02.000Z",
      },
    ],
  },
]

Environment

  • mysql
    Sequelize version: 5.6.1

Activity

  1. papb commented on Aug 1, 2019

    @papb
    Member

    Hello! Can you please post:

    • What SQL query was generated by Sequelize

    • What SQL query you wanted it to generate instead

    Thanks!

  2. added
    status: awaiting response
    type: bug
    on Aug 1, 2019
  3. papb commented on Aug 1, 2019

    @papb
    Member

    Also, can you please test this with another dialect? This is important to know whether the problem is dialect-specific or not.

    You can instantiate an in-memory SQLite instance very easily:

    1. npm install sqlite3
    2. new Sequelize('sqlite::memory:')

    You can instantiate a local postgres instance very easily:

    1. Run a local postgres
      • On windows: PostgreSQLPortable_10.4.1.zip (no need to install, just unzip and run)
        • Run the .exe and then CREATE DATABASE testdb; (don't close the .exe)
      • On linux (with docker): docker pull postgres && docker run --rm --name pg -d -p 5432:5432 postgres
        • Run docker exec -t pg psql -U postgres -c 'CREATE DATABASE testdb;'
    2. new Sequelize('postgres://postgres@localhost:5432/testdb')
  4. added
    dialect: mysql
    on Aug 1, 2019
  5. github-actions commented on Nov 11, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  6. added theissue type on Mar 9, 2025
  7. removed
    type: bug
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dialect: mysqlstatus: awaiting response

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions