序列计数关联

时间:2018-11-05 17:03:18

标签: postgresql sequelize.js sequelize-typescript

我想用一个称为标记的表来计算城市协会,但是当我调用上面的代码时,我遇到了上面的错误。该错误不够明显。我在两个表中都有FrozenTableName选项

  

TypeError:attr [0] .indexOf不是函数

城市模型:

            const models = require('../models2');
            module.exports = (sequelize, DataTypes) => {
              const City = sequelize.define('city', {
              name: { type: DataTypes.STRING, allowNull: false },
                status: { type: DataTypes.INTEGER, allowNull: false },
                latitude: { type: DataTypes.BIGINT, allowNull: false },
                longitude: { type: DataTypes.BIGINT, allowNull: false },

              }, { freezeTableName: true});
              City.associate = function(models) {
                // associations can be defined here
                 City.hasMany(models.marker,{as: 'markers', foreignKey: 'cityId'})
              };
              return City;
            };

标记模型:

            module.exports = (sequelize, DataTypes) => {
              const Marker = sequelize.define('marker', {
                description: { type: DataTypes.STRING, allowNull: false },
                status: { type: DataTypes.INTEGER, allowNull: false },
                latitude: { type: DataTypes.BIGINT, allowNull: false },
                longitude: { type: DataTypes.BIGINT, allowNull: false },
                cityId: {
                   type: DataTypes.INTEGER,
                   references: {
                      model: 'city',
                      key: 'id',
                   }
                }

              }, { freezeTableName: true});
              Marker.associate = function(models) {
                // associations can be defined here
              };
              return Marker;
            };

顺序查询

            City.findAll({
                   attributes: [
                     'name',
                     [sequelize.fn('count', sequelize.col('marker.cityId')) ,'marker_count']
                   ],
                   include: [
                   {
                      model: Marker, as: "markers" ,
                      attributes: [] // <----- Make sure , this should be empty
                   }
                  ]
              }).then(cities => res.status(201).send(cities))
                .catch(error => {
                    console.log(error);
                    res.status(400).send(error)
              });

1 个答案:

答案 0 :(得分:0)

我认为您应该更改属性中的表名:

sequelize.col('marker.cityId'))

sequelize.col('markers.cityId'))