sequelize.js - 与包含在 Sequelize 中相关的限制和偏移

标签 sequelize.js

我有 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需要选择。否则,您将收到此错误:

https://github.com/sequelize/sequelize/issues/7514



你也可以引用:

https://github.com/sequelize/sequelize/issues/4772

关于sequelize.js - 与包含在 Sequelize 中相关的限制和偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52102085/

相关文章:

sequelize.js - Sequelize - 带有两个嵌套包含的嵌套列语法

javascript - 使用 Sequelize.js findAll 对连接表中的字段进行排序的正式且正确的语法

node.js - 使用sequelize在jade中查找

node.js - 如何使用Sequelize.js建立表之间的多对多关系?

javascript - Sequelize.js:如何查询 N:M 关系

mysql - 检查对象是否存在时, Node Sequelize 抛出未定义的错误

mysql - 连接 Sequelize 到 MySQL 生成访问被拒绝错误

javascript - 发送明确的错误消息作为响应

javascript - 如何在 Sequelize (Node js) 中关联对象?

javascript - Sequelize 类型错误 : Cannot read property '1' of null