首页 > 解决方案 > 续集计数关联

问题描述

我想用一个名为标记的表来计算城市关联,但是当我调用上面的代码时,我遇到了上面的错误。错误不够明确。我在两个表中都有 freezeTableName 选项

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

标签: postgresqlsequelize.jssequelize-typescript

解决方案


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

sequelize.col('marker.cityId'))

sequelize.col('markers.cityId'))

推荐阅读