我有2个国家,城市模型。
它们彼此相关联。城市属于国家。现在我想做的是在国家查询中获取城市列表以及可能的分页限制和偏移量。
如果我在下面,它将列出一个国家内的所有城市。我需要做的是能够限制城市的限制和抵消参数。
Country.findById(1, {
include: [
{
model: City,
as: 'cities'
}
]
});
国家模式
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;
}
城市模型
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"]
}
]
});
这将有效,但需要选择“countryId”,否则您将收到此错误
你也可以从这里参考。
干得好 :
Country.findById(1, {
include: [
{
attributes : ["id", "countryId", "name"]
model: City,
as: 'cities' ,
separate: true,
offset: 5, // <--- OFFSET
limit: 5 // <--- LIMIT
}
]
});
更多细节:DO READ