Sequelize literal with limit 和 offset 参数不正确的查询

Sequelize literal with limit and offset params incorrect query

我有下一个模型:

const Picture = sequelize.define<IPictureInstance>('picture', {
 id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
 img: { type: DataTypes.STRING, allowNull: false },
 mainTitle: { type: DataTypes.STRING, allowNull: false },
 description: { type: DataTypes.TEXT }
});

const PictureType = sequelize.define('pictureType', {
 id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
 name: { type: DataTypes.STRING }
});

他们的关系:

PictureType.hasMany(Picture);
Picture.belongsTo(PictureType);

我正在尝试获取包含图片数量的 op pictureTypes 列表,为此,我创建了下一个查询:

const pictureTypes = await models.PictureType.findAll({
  attributes: {
    include: [
      [Sequelize.literal(`(SELECT COUNT(*) FROM pictures AS picture WHERE picture.pictureTypeId = pictureType.id)`), "picturesAmount"]
    ]
  },
  limit: limitValue,
  offset: offsetValue
});
 return pictureTypes;
};

但结果我收到了下一条消息:“столбец picture.picturetypeid не существует”,翻译为:“列 picture.picturetypeid 不存在”。

问题是什么?将不胜感激。

根据您的 DBMS,您需要将具有特殊字符或混合大小写的列包装到 "(通常是 PostgreSQL)或反引号(MySQL)中,这样 DBMS 会解释此列名称,也不会尝试将其转换为小写。

const pictureTypes = await models.PictureType.findAll({
  attributes: {
    include: [
      [Sequelize.literal(`(SELECT COUNT(*) FROM pictures AS picture WHERE picture."pictureTypeId" = pictureType.id)`), "picturesAmount"]
    ]
  },
  limit: limitValue,
  offset: offsetValue
});
 return pictureTypes;
};