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'
}
]
});
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Country.findById(1, {
include: [
{
model: City,
as: 'cities',
limit: 1,
attributes: ["id", "countryId", "name"]
}
]
});
Run Code Online (Sandbox Code Playgroud)
这将起作用,但countryId需要选择。否则,您将收到此错误:
你也可以参考:
| 归档时间: |
|
| 查看次数: |
9896 次 |
| 最近记录: |