Repository navigation
Closed
Labels
topic: limit & offsetFor issues and PRs. Things that involve queries with limit and/or offset.type: bugDEPRECATED: replace with the "bug" issue type
Description
The models I've created:
var Post = sequelize.define('post', {
title: Sequelize.STRING,
content: Sequelize.TEXT
}),
User = sequelize.define('user', {
username: Sequelize.STRING
}),
Interest = sequelize.define('interest', {
name: Sequelize.STRING
})
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'})
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'})
User.belongsToMany(Interest, {as: 'interests', through: 'users_interests'})
Interest.belongsToMany(User, {as: 'users', through: 'users_interests'})inserted data:
sequelize.sync({force: true}).then(function(){
var chainer = new Sequelize.Utils.QueryChainer()
async.auto({
users: function(callback) {
User.bulkCreate([
{username: "tyler"},
{username: "skyler"},
{username: "hector"}
]).done(function(){
User.findAll().done(callback)
})
},
posts: ['users', function(callback, result) {
Post.bulkCreate([
{title: "a", content: "aaa"},
{title: "b", content: "bbb"}
]).done(function(){
Post.findAll().then(function(posts) {
chainer.add(posts[0].setAuthor(result.users[1]))
chainer.add(posts[1].setAuthor(result.users[0]))
chainer.run().done(callback)
})
})
}],
interests: function(callback) {
Interest.bulkCreate([
{name: "walking"},
{name: "sleeping"},
{name: "hunting"},
]).done(function(){
Interest.findAll().done(callback)
})
},
users_interests: ['users', 'interests', function(callback, result) {
chainer.add(result.users[0].setInterests([result.interests[1]]))
chainer.add(result.users[2].setInterests([result.interests[0], result.interests[2]]))
chainer.run().done(callback)
}]
})
}).catch(function(error) {
console.error(error)
})now I like to get all posts from users who have the interest sleeping, using limit and offset. I do it as follows:
Post.findAll(
{
limit: 3, offset: 0,
include: [{model: User, as: 'author', where: {}, include: [
{model: Interest, as: 'interests', where: {name: 'sleeping'}}
]}]
})
.then(function(posts) {
res.json(posts)
})
.catch(function(error) {
next(error)
})error:
Unknown column 'user.userId' in 'where clause'
SequelizeDatabaseError: Unknown column 'user.userId' in 'where clause'
at module.exports.Query.formatError (/home/ich/express/node-app/node_modules/sequelize/lib/dialects/mysql/query.js:158:16)
at Query.results.on.on.on.alreadyEnded (/home/ich/express/node-app/node_modules/sequelize/lib/dialects/mariadb/query.js:99:30)
at Query.emit (events.js:95:17)
at Client.fnQueryErr (/home/ich/express/node-app/node_modules/mariasql/lib/Client.js:129:36)
at Client.emit (events.js:95:17)
at Client._processQueries (/home/ich/express/node-app/node_modules/mariasql/lib/Client.js:340:20)
at /home/ich/express/node-app/node_modules/mariasql/lib/Client.js:239:38
at process._tickCallback (node.js:442:13)It works when I cut out limit and offset, OR the the where clause in the included. The same applies for findAndCountAll()
node v0.10.35
[email protected]
[email protected]
Reacted by Ronan, Charlie Henin, Greg, Sean Newell, Ihor Sakayliuk, Ryan Lindgren, Mohammad Mahmoodi and Mohammad Moradi
Metadata
Metadata
Assignees
Labels
topic: limit & offsetFor issues and PRs. Things that involve queries with limit and/or offset.type: bugDEPRECATED: replace with the "bug" issue type
Activity
mickhansen commentedon Jan 26, 2015
Are you refering to the empty where on the user include or the where on the nested interest include?
igittGit commentedon Jan 26, 2015
To both. I can't use
wherein any of this cases iflimitandoffsetis used, evenwhere: {}seems to break it. The only place I can use it is the firstwhereclause which I haven't used in this scenario.mickhansen commentedon Jan 26, 2015
@igittGit we have quite a few tests that work with using
include.whereand `limit'.https://github.com/sequelize/sequelize/blob/master/test/integration/include/findAll.test.js#L1186 is one example.
But limits are still complicated because they enforce the use of subqueries.
Looks like you've found a case where we don't have full coverage yet.
OlivierCuyp commentedon Feb 5, 2015
I also have same kind of issue when adding limit and offset after an include.
It seems the JOINed tables are missing in sub-query in the generated SQL.
Here is my case (using sequelize 2.0.0-rc8):
The SQL
The error
brejnko commentedon Mar 6, 2015
I have similar issue. Two tables with many to may relationship, ItemGroup and Amenity who are connected:
When i do query with condition:
I get the expected query and result but if I add limit in the condition this error apears:
Using:
iojs 1.4.3
sequelize 2.0.3
postgresql 9.3
mogusbi commentedon Aug 4, 2016
Has this bug been fixed? I'm having the same issue with version 3.23.4
Generated SQL statement
and the error
Models:
janmeier commentedon Sep 28, 2016
@scottbeacher Issue is still open, so no :)
A subquery is needed when you want to limit includes or for cartesian joins - And the logic for subqueries can be complicated.
Bazze commentedon Oct 20, 2016
Would you say that the recommended workaround is to write a raw SQL query for the cases where you encounter this issue?
janmeier commentedon Oct 20, 2016
@Bazze It's hard to say in general, but sometimes yes - We use sequelize at snaplytics, and sometimes we also resort to writing raw queries - Especially for aggregates.
Sometimes you can also go semi-raw and use
sequelize.queryInterface.QueryGenerator.selectQueryandsequelize.queryInterface.QueryGenerator.whereItemsQueryto generate parts of the queryBazze commentedon Oct 20, 2016
Thanks @janmeier. Do you have any example you could share where you use those helper methods? Or do you know if it's documented anywhere? If not I'll just start digging into the source code.
janmeier commentedon Oct 20, 2016
It's not documented anywhere - We'd like to make query generation part of the public API at some point, but currently its not.
One (simplified) example would be that you have a where clause that is generated dynamically, so you don't know how many items it contains, or maybe it contains stuff like
$gt: 42, and you don't want to glue it together yourselfThis is of course a bit contrieved, since this query could be easily expressed in sequelize, but I hope you get the idea ;)
sequelize/lib/dialects/abstract/query-generator.js
Line 1737 in 6f63728
Bazze commentedon Oct 20, 2016
Great, thanks @janmeier. I'll give it a try. In other projects I've often ended up pulling in knex for building raw queries when I need to circumvent the ORM, maybe I don't have to this time.
drunkhacker commentedon Dec 13, 2016
for my own case, when I remove the LEFT OUTER JOIN by adding
required: truefor every includes i need it worked.ventr1x commentedon Jun 4, 2017
This is a rather big issue as the only "workaround" would be to load the entire table and splice the array. Try to do that on a table with millions of entries.. I hope you have some ram and cpu time to spare..
This happens on EVERY kind of pagination attempt, if the data is somehow associated and has a where in it.
I also don't get what's so hard about this to change? The limit/offset currently are applied to the include subquery, it just has to be applied to the main query (or the last inner join). There is NO need for another query or something.
The offset/limit currently is simply applied to the wrong sub query. This is a clear bug in sequelize and not just a feature request.
Example:
Wrong:
correct:
Generated by:
35 remaining items
chornbe commentedon Nov 25, 2017
Why not just change the basic model so it eliminates joins and always does (sub)queries with reasonable limits in place; while that seems rather drastic on casual read, it actually solves every problem in this thread (and a few other discussions I've seen), and you can impose reasonable limits (or not!) on the (sub)queries, manually "joining" them by inserting them into the parent query's results as another field, and you can then break the reliance on the associations where you might not have control over such things.
I can't reasonably think of anything that's not a crazy edge case where this wouldn't be a preferable model, especially since the sequelize "include: [....]" syntax seems WAY more comfortable for sub/new queries and not even a little bit comfy for joins.
Am I way off base, here? At this point, I'm just doing my own queries, and gluing the results together in my biz-logic API before handing back the results.
IMO, this particular issue with limits shows the weakness of the inferred joins vs. the explicit sub-/multi-query model.
$.02
Alexsey commentedon Jan 26, 2018
Linking second biggest discussions on this one #7344
BTW in #7344 we have set a bounty on this one. May be some one from here would also like to participate
smithaitufe commentedon Feb 6, 2018
In my case, adding
duplicating: falsesolves the issue.Observations
It prevents it from generating subquery
Code Sample
baozdemir commentedon Feb 14, 2018
duplicating: false
it worked for me
arturslogins commentedon Feb 16, 2018
Any progress on this issue?
arturslogins commentedon Feb 16, 2018
@smithaitufe thanks for solution
saurabhverma2892 commentedon Feb 27, 2018
still an issue. Solved it in my case by putting required:true in all includes, but its not the best way since the onces not having the included objects dont come in the result.
sushantdhiman commentedon Mar 22, 2018
This is fixed by #9188 , I request thread participants to verify this
yashdabi commentedon Nov 11, 2019
#9869 (comment)
lehoangthanh commentedon Feb 26, 2021
@smithaitufe
duplicating: false
it worked for me
Thank you.
agSant01 commentedon Mar 18, 2021
@smithaitufe
duplicating: falseinside of the include models worked for me too
Thank you guys for the thread.
Still, not mention of it in the official Docs.
cucchi10 commentedon Oct 20, 2022
duplicating: falsedoesn't work for me.
I was able to fix it with
subQuery: falseMehmedalicaliskan commentedon Mar 10, 2024
I have examined the pagination problem with associated where clause problems in this article.
https://malicaliskan.medium.com/e50dbc9de01d
You can find why the problem occurs, in what conditions and what can be an easy solution to the issue in the article.