【发布时间】:2023-03-20 01:51:01
【问题描述】:
我正在使用 sequelize 访问 postgres 数据库,我想查询一个城市,例如包括“建筑物”表,但我想将输出重命名为“建筑物”并返回 http 响应,但我有这个错误:
{ SequelizeEagerLoadingError: building 使用别名关联到城市。你已经 e 包含一个别名(建筑物),但它与您的 a 中定义的别名不匹配 协会。
City.findById(req.params.id,{
include: [
{
model: Building, as: "buildings"
}
]
}).then(city =>{
console.log(city.id);
res.status(201).send(city);
}) .catch(error => {
console.log(error);
res.status(400).send(error)
});
城市模型
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.building,{as: 'building', foreignKey: 'cityId'})
};
return City;
};
【问题讨论】:
-
检查别名
buildings是否与定义相同,请同时发布城市型号代码 -
哦我明白了,别名必须与模型匹配?如果更改模型中的别名,是否必须创建 sequelize 迁移?
-
不,只要改名字就行了,瞧,你很高兴
-
非常感谢!成功了!
标签: node.js postgresql sequelize.js sequelize-cli sequelize-typescript