postgresql - 续集计数关联
问题描述
我想用一个名为标记的表来计算城市关联,但是当我调用上面的代码时,我遇到了上面的错误。错误不够明确。我在两个表中都有 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)
});
解决方案
我认为您应该更改属性中的表名:
sequelize.col('marker.cityId'))
至
sequelize.col('markers.cityId'))
推荐阅读
- javascript - 为什么当我点击提交时表单的参数消失了?
- java - 版本冲突,当前版本 [2] 与提供的版本 [1] 不同
- asp.net - 如何在其他函数上使用变量
- regex - 正则表达式:如何在某个字符之前的括号内获取所有内容?
- python-3.x - 仅从具有十六进制字符的字节编码 python 字符串中获取 ASCII 值
- c# - Flurl 的 PostUrlEncodedAsync 忽略 JsonProperty 名称
- python - 未排序的段 argmax 解决方法 tensorflow
- excel - 我想检查数据表上是否存在时间重叠
- javascript - 将防伪令牌附加到 XMLHttpRequest
- javascript - 如何在像uploadify 这样的dropzone 中添加数据?