Limit and offset in association with include in sequelize

 ̄綄美尐妖づ 提交于 2019-12-24 00:22:47

问题


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;
}

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/52102085/limit-and-offset-in-association-with-include-in-sequelize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!