选择并包含另一个表别名

问题描述 投票:0回答:1

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

{ SequelizeEagerLoadingError:建筑物使用别名与城市关联。你是 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;
            };
node.js postgresql sequelize.js sequelize-cli
1个回答
64
投票

正如您在下面的代码中定义的别名是

building
:

City.hasMany(models.building,{as: 'building', foreignKey: 'cityId'})

但是在查询中,您正在使用

buildings

include: [
  {
     model: Building, as: "buildings" // <---- HERE
  }
]

应该是

building

include: [
   {
         model: Building, as: "building" // <---- HERE
   }
]
© www.soinside.com 2019 - 2024. All rights reserved.