Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit and offset in association with include in sequelize

Tags:

sequelize.js

I have 2 models Country, City.

They are associated with each other. City Belongs to Country. Now what I want to do is get cities list within a country query along with limit and offset for pagination if possible.

If i do below it will list all cities within a country. What I need to do is be able to limit cities with limit and offset params.

Country.findById(1, {
  include: [
    { 
      model: City,
      as: 'cities'
    }
  ]
});

Country Model

module.exports = (sequelize, DataTypes) => {
    let Country = sequelize.define('Country', {
        id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
        code: {type: DataTypes.STRING, allowNull: false, unique: true },
        name: DataTypes.STRING
    });
    Country.associate = (models) => {
        Country.hasMany(models.City, {as: 'cities'});
    };
    return Country;
}

City Model

module.exports = (sequelize, DataTypes) => {
    let City = sequelize.define('City', {
        id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
        name: {type: DataTypes.STRING, allowNull: false, unique: true},
    });

    City.associate = (models) => {
        City.belongsTo(models.Country, {as: 'country'});
    };

    return City;
}
like image 624
Yalamber Avatar asked Aug 30 '18 16:08

Yalamber


2 Answers

Country.findById(1, {
  include: [
    { 
      model: City,
      as: 'cities',
      limit: 1,
      attributes: ["id", "countryId", "name"]
    }
  ]
});

This will work, but countryId needs to be selected. Otherwise, you will get this error:

https://github.com/sequelize/sequelize/issues/7514

You can also refer to:

https://github.com/sequelize/sequelize/issues/4772

like image 119
Rahul Sharma Avatar answered Oct 19 '22 03:10

Rahul Sharma


Here you go :

Country.findById(1, {
  include: [
    { 
        attributes : ["id", "countryId", "name"]     
        model: City,
        as: 'cities' ,
        separate: true,
        offset: 5, // <--- OFFSET
        limit: 5 // <--- LIMIT
    }
  ]
});

For more detail : DO READ

like image 1
Vivek Doshi Avatar answered Oct 19 '22 01:10

Vivek Doshi