Thursday, 27 April 2017

How to specify limit for belongsToMany association in Sequelizejs?

I have a model Actor, and I need to load only 10 most recent of his movies

const result = await db.Actor.findAll({
  where: { id: actorId },
  include: [{
    model: db.Movie,
    as: 'movies',
    through: { attributes: [] },
    limit: 10,
  }],
})

When I try to add limit option it throws an error: Only HasMany associations support include.separate

Model:

 export default function(sequelize, DataTypes) {
  const Actor = sequelize.define('Actor', {
    // attributes
  }, {
    tableName: 'actors',
    timestamps: true,
    classMethods: {
      associate(models) {
        Actor.belongsToMany(models.Movie, {
          through: models.ActorMovie,
          foreignKey: { name: 'movieId', field: 'movie_id', allowNull: false },
          as: 'movies',
        })
      },
    },
  })

  return Actor
}

Is there a way to limit included belongsToMany association for findAll?



via Kossgreim

No comments:

Post a Comment