gpt4 book ai didi

node.js - Sequelize 选择并包含另一个表别名

转载 作者:搜寻专家 更新时间:2023-11-01 00:35:37 26 4
gpt4 key购买 nike

我正在使用 sequelize 访问 postgres 数据库,我想查询一个城市,例如包含“Building”表,但我想将输出重命名为“buildings”并返回 http 响应,但我有这个错误:

{ SequelizeEagerLoadingError: building is associated to city using an alias. You'v e included an alias (buildings), but it does not match the alias defined in your a ssociation.

    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
}
]

关于node.js - Sequelize 选择并包含另一个表别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53117988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com