字段列表中的未知列sequelize

时间:2018-05-21 20:24:36

标签: node.js sequelize.js

我尝试使用Sequelize执行以下查询:

db.Post.findAll({
      include: [
        {
          model: db.User,
          as: 'Boosters',
          where: {id: {[Op.in]: a_set_of_ids }}
        },
        {
          model: db.Assessment,
          as: 'PostAssessments',
          where: {UserId: {[Op.in]: another_set_of_ids}}
        }
      ],
      attributes: [[db.sequelize.fn('AVG', db.sequelize.col('Assessments.rating')), 'average']],
      where: {
        average: 1
      },
      group: ['id'],
      limit: 20
    })

但我遇到了这个错误:" ER_BAD_FIELD_ERROR"。未知栏目'评估评估'在'字段列表',虽然我有表"评估"在数据库和"评级"是该表中的一列。

My Post模型如下所示:

const Post = sequelize.define('Post', {
title: DataTypes.TEXT('long'),
description: DataTypes.TEXT('long'),
body: DataTypes.TEXT('long')
  }, {
  timestamps: false
    });

  Post.associate = function (models) {
    models.Post.belongsToMany(models.User, {as: 'Boosters', through: 'UserPostBoosts' });
    models.Post.hasMany(models.Assessment, {as: 'PostAssessments'});
  };

我做错了什么?

2 个答案:

答案 0 :(得分:1)

当我们在查找查询中有限制时,似乎会出现此问题,其中包含关联模型(当我们从查询中删除限制时,上述错误不会显示)。为了解决这个问题,我们可以将一个选项subQuery:false传递给find。 (https://github.com/sequelize/sequelize/issues/4146

如果有人遇到同样的问题,这是正确的查询:

db.Post.findAll({
  subQuery: false,
  include: [
    {
      model: db.User,
      as: 'Boosters',
      where: {id: {[Op.in]: a_set_of_ids }}
     }
    ,{
      model: db.Assessment,
      as: 'PostAssessments',
      where: {UserId: {[Op.in]: another_set_of_ids}}
    }
  ],
  having: db.sequelize.where(db.sequelize.fn('AVG', db.sequelize.col('PostAssessments.rating')), {
       [Op.eq]: 1,
     }),
  limit: 20,
  offset: 2,
  group: ['Post.id', 'Boosters.id', 'PostAssessments.id']
})

答案 1 :(得分:0)

错误与此相关:

models.sequelize.col('Assessments.rating'))

将其更改为

models.sequelize.col('PostAssessments.rating')) // or post_assessments.rating

原因:您正在使用包含as: 'PostAssessments',的别名。