与 include in sequelize 相关的限制和偏移 [英] Limit and offset in association with include in sequelize

查看:13
本文介绍了与 include in sequelize 相关的限制和偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个模型 Country,City.

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'
    }
  ]
});

国家模式

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.否则,你会得到这个错误:

This will work, but countryId needs to be selected. Otherwise, you will get this error:

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

也可以参考:

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

这篇关于与 include in sequelize 相关的限制和偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆