【问题标题】:Limit and offset in association with include in sequelize与 include in sequelize 相关的限制和偏移
【发布时间】:2019-02-05 16:44:01
【问题描述】:

我有 2 个模型 Country,City。

它们相互关联。城市属于国家。现在我想做的是获取国家查询中的城市列表以及分页的限制和偏移量(如果可能)。

如果我在下面这样做,它将列出一个国家/地区的所有城市。我需要做的是能够使用限制和偏移参数来限制城市。

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;
}

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:
    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

    【讨论】:

    • 我看到了limit选项,我们也可以设置offset吗?还要使用限制,我想我们需要在包含参数中使用单独的:true。
    • 不,在 3.1 版本之后它不是强制性的。让我检查一下偏移量
    • 我还没有找到传递偏移量的选项。
    • 我在我的项目中使用过它并且它正在工作,不知道文档:D
    【解决方案2】:

    给你:

    Country.findById(1, {
      include: [
        { 
            attributes : ["id", "countryId", "name"]     
            model: City,
            as: 'cities' ,
            separate: true,
            offset: 5, // <--- OFFSET
            limit: 5 // <--- LIMIT
        }
      ]
    });
    

    更多详情:DO READ

    【讨论】:

    • 这会起作用,但是对于 1 级,我认为如果你再深入一点,它可能会导致一些问题。为此,您必须检查该运行时间。
    • 请检查限制也仅在 1 级有效。不是偏移量
    • @RahulSharma ,不,它可以在嵌套级别上工作,我在我的项目中也使用了它
    • 在文档中我看到有关于限制的信息,但没有关于偏移的信息。 @VivekDoshi 也可以抵消吗?我也会测试一下
    • @Yalamber 你测试过吗?
    【解决方案3】:

    我将发布某种更新(实际上并没有那么更新)的答案。

    嵌套包含中的偏移和限制工作就像它们在顶层工作一样。

    我已经用 2 个级别的嵌套包含对它们进行了测试,比如

    User.findOne(
    {
     where: {id: 1},
      include: 
        [ 
         {
          model: Tasks,
          include:
            [
             {
               model: Unfinished, limit: 3, offset: 10
             }
            ]
         }
        ]
    });
    

    现在的问题是这没有记录(或者至少我没有找到任何文档),如果你使用 Typescript,它会给你错误,所以你必须将选项对象转换为 any,但它可以工作正如预期的那样(至少对我来说)!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      相关资源
      最近更新 更多