node.js - 续集选择并包含另一个表别名
问题描述
我正在使用 sequelize 访问 postgres 数据库,我想查询一个城市,例如包括“建筑”表,但我想将输出重命名为“建筑”并返回 http 响应,但我有这个错误:
{ SequelizeEagerLoadingError: 建筑物使用别名与城市相关联。您已包含一个别名(建筑物),但它与您的 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;
};
解决方案
正如您在下面的代码中定义的别名一样building
:
City.hasMany(models.building,{as: 'building', foreignKey: 'cityId'})
但是在查询中,您正在使用buildings
include: [
{
model: Building, as: "buildings" // <---- HERE
}
]
它应该是building
:
include: [
{
model: Building, as: "building" // <---- HERE
}
]
推荐阅读
- amazon-web-services - CDK 有没有办法向通过 Cognito 身份验证的用户授予 S3 访问权限
- api - 如何使用 cURL 更快地发送许多 POST 请求
- excel - VBA Excel 循环遍历同一目录中的所有 .xslm 文件
- java - 围绕javaFX中的枢轴旋转对象
- c# - OpenFileDialog - 如何在c#中选择文件后将文件路径设置为输入类型=文本元素
- python - 从类方法模拟/修补计算属性的值
- xml - 使用计算出的 xsl:variables 运行 Total?
- r - R 闪亮、可缩放的树状图程序
- python - 将字典嵌套到数据框中
- python - 并行化函数的问题(LSTM 模型)