我有 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
需要选择。否则,您将收到此错误:你也可以引用:
关于sequelize.js - 与包含在 Sequelize 中相关的限制和偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52102085/