Repository navigation
Open
Labels
Great SSCCEThis issue has a great SSCCE/MCVE/reprex posted and therefore deserves extra attention! :)dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).type: featureDEPRECATED: replace with the "feature" issue type
Description
What are you doing?
Ordering or limiting by an associated model. Example here would be:
find the 10 brands with the best reviewed stores
Other examples might be:
- find users who most recently posted
- find brands with stores closest to me
- find products that were most recently purchased
Lots of cases where you want to find a distinct set of a model, ordered by a property of an associated model.
'use strict'
const _ = require('lodash')
const Sequelize = require('sequelize')
const sequelize = new Sequelize(process.env.DATABASE_URL, { dialectOptions: { ssl: true }, logging: false })
// a brand name, like a store, or restaurant chain
sequelize.define('brand', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
name: Sequelize.STRING
})
// an individual real-world location, a store, or restaurant
sequelize.define('store', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
score: Sequelize.INTEGER,
brandId: Sequelize.INTEGER
})
sequelize.models.brand.hasMany(sequelize.models.store)
sequelize.models.store.belongsTo(sequelize.models.brand)
const main = async () => {
await sequelize.sync()
await sequelize.models.store.destroy({ truncate: true, cascade: true })
await sequelize.models.brand.destroy({ truncate: true, cascade: true })
// create 22 test brands
const testbrands = _.range(22).map(i => ({ name: `Brand ${i}` }))
await sequelize.models.brand.bulkCreate(testbrands, { returning: true })
const brands = await sequelize.models.brand.findAll()
// create 4 stores, each with a random score, for each brand
const teststores = brands.reduce((array, brand) => {
const brandstores = _.range(4).map(i => ({ brandId: brand.id, score: brand.id * 10 + _.random(1, 9) }))
return [...array, ...brandstores]
}, [])
const stores = await sequelize.models.store.bulkCreate(teststores)
// find the 10 brands with the highest scores
const nearestBrands = await sequelize.models.brand.findAll({
attributes: ['name'],
include: [
{
model: sequelize.models.store,
order: [sequelize.col('score'), 'DESC']
}
],
limit: 10,
order: [[sequelize.models.store, sequelize.col('score'), 'DESC']],
logging: console.log
})
console.log(nearestBrands.map(b => [b.name, b.stores[0].score]))
await sequelize.close()
}
main()To Reproduce
Steps to reproduce the behavior:
- run code sample above which creates model and test data
- See response returns brands 9..0
What do you expect to happen?
Returns brands 21..12
SELECT *
FROM brands
JOIN (
SELECT DISTINCT ON ("brandId") *
FROM stores
ORDER BY "brandId", score DESC
) AS stores
ON brands.id = stores."brandId"
ORDER BY stores.score DESC
LIMIT 10;What is actually happening?
Returns brands 9..0
SELECT
"brand".*,
"stores"."id" AS "stores.id",
"stores"."score" AS "stores.score",
"stores"."brandId" AS "stores.brandId",
"stores"."createdAt" AS "stores.createdAt",
"stores"."updatedAt" AS "stores.updatedAt"
FROM (
SELECT
"brand"."id",
"brand"."name"
FROM
"brands" AS "brand"
LIMIT 10
) AS "brand"
LEFT OUTER JOIN "stores" AS "stores" ON "brand"."id" = "stores"."brandId"
ORDER BY "stores"."score" DESC;Environment
Dialect:
- mysql
- postgres
- sqlite
- mssql
- any
Dialect library version: XXX
Database version: XXX
Sequelize version: 4.35.2
Node Version: 12.6.0
OS: Linux
If TypeScript related: TypeScript version: XXX
Tested with latest release: - No
- Yes, specify that version:
Reacted by Anthony DOWTK, Anthony Sennett, Andreas Lind, Rabia Asif, Pedro Augusto de Paula Barbosa, Liam Myles, Nathan Hyatt, agl, dujm, joaopedrobuzatti and 6 more
Metadata
Metadata
Assignees
Labels
Great SSCCEThis issue has a great SSCCE/MCVE/reprex posted and therefore deserves extra attention! :)dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).type: featureDEPRECATED: replace with the "feature" issue type
Type
Projects
- StatusShow more project fieldsNo status
Activity
papb commentedon Aug 6, 2019
I was able to reproduce in the latest version.
But if this would be "fixed", it would be a breaking change... I can also see usage for the current behavior, no? Perhaps this should be considered a feature instead of a bug?
mmmmmrob commentedon Aug 7, 2019
@papb I can see it could be a breaking change. I'd be super happy to simply be told I'm approaching it wrong. The essence of the problem is how to I get a limited set of model A, sorted by a property of associated model B.
securedeveloper commentedon Aug 12, 2019
@mmmmmrob same thing happened to me, was trying to debug and find what I was doing wrong, until I realised it doesn't work at all. Would love to create a feature PR.
packlikez commentedon Aug 13, 2019
Same problem here.
papb commentedon Aug 13, 2019
@securedeveloper If you are willing to submit a PR, that would be great!! Even better if you make it a feature rather than a change.
8 remaining items
packlikez commentedon Sep 2, 2019
When I order with literal it's work but when I use [Model,'DESC'] it's put order only the outside
github-actions commentedon Nov 8, 2021
This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂
tsai121594 commentedon Feb 5, 2022
I spent hours on this. Workaround that worked for me is,
order: [['includeTable1', 'includeTable2', 'column', 'ASC']]This is three nested query. My query looked like
table.findAll(include: {..., as: includeTable1, include: {..., as:includeTable2}}, order: [['includeTable1', 'includeTable2', 'column', 'ASC']])ThierryVC commentedon Oct 7, 2022
I tried both
[email protected]&[email protected]with mysqlUsing limit, this did not work:
translated to sql:
with error:
Unknown column 'adminNotice.sendOn' in 'order clause'Commenting out the limit made it succeed, turning it into
But needing the limit, I found that this would work:
turning the sql into:
shubhanshu-ssipmt commentedon Jan 11, 2024
you can try using seperate: true in included model
shubhanshu-ssipmt commentedon Jan 11, 2024
try using seperate: true
m3hransh commentedon Mar 7, 2024
Based on this
https://stackoverflow.com/questions/43729254/sequelize-limit-and-offset-incorrect-placement-in-query
You can use
Somehow avoiding nested query fixed the problem for me.
jatin-garg-repo commentedon May 8, 2024
It works but it reduces the results and not give required limited counted results
ingbioservicios commentedon Aug 1, 2024
Algún avance en este tema.
Funciona pero reduce los resultados y no proporciona los resultados contados limitados requeridos.
acolchagoff commentedon Jan 31, 2025
The idea that a paged set of results is impossible if you sort by a column joined from another table is surprising to me, it's such a common use case.