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;
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With