I'm using Sequelize 5 as an ORM for my GraphQL API but I've run into a performance issue when querying associated data.
Let's say I have a User
which has many Post
s, so my model definitions look like this:
class User extends Model { }
User.init({ name: Sequelize.STRING }, { sequelize });
class Post extends Model { }
Post.init({ content: Sequelize.STRING }, { sequelize });
User.hasMany(Post);
Now I have fetched a User
model from the database and I want to query an x
amount of posts from this user. I know I can fetch all posts using user.getPosts()
, but that would return way more records than I need.
I have found this answer which explains how to apply a limit when eager loading the relation using the include
option, but in my case I would like to lazy load the relation. The reason for this is because of how GraphQL resolvers work.
So my question is: How do I get the first x
posts of a user?
I'm using Sequelize 5 as an ORM for my GraphQL API but I've run into a performance issue when querying associated data.
Let's say I have a User
which has many Post
s, so my model definitions look like this:
class User extends Model { }
User.init({ name: Sequelize.STRING }, { sequelize });
class Post extends Model { }
Post.init({ content: Sequelize.STRING }, { sequelize });
User.hasMany(Post);
Now I have fetched a User
model from the database and I want to query an x
amount of posts from this user. I know I can fetch all posts using user.getPosts()
, but that would return way more records than I need.
I have found this answer which explains how to apply a limit when eager loading the relation using the include
option, but in my case I would like to lazy load the relation. The reason for this is because of how GraphQL resolvers work.
So my question is: How do I get the first x
posts of a user?
2 Answers
Reset to default 8You can pass additional find
options to the getter. This is not well documented, though briefly mentioned here. So you can just do:
user.getPosts({
limit: 10,
offset: 100,
where: { /* whatever */ },
order: [ /* whatever */ ],
transaction,
etc.
})
I would expect there to be a more fluent interface for this, but I've currently solved this simply with:
return db.models.posts.findAll({
where: { userId: user.id },
limit: x,
});