最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Limiting lazy loaded associations in Sequelize - Stack Overflow

programmeradmin5浏览0评论

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 Posts, 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 Posts, 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?

Share asked Oct 26, 2019 at 20:36 Duncan LukkenaerDuncan Lukkenaer 14.1k18 gold badges71 silver badges107 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

You 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,
});
发布评论

评论列表(0)

  1. 暂无评论