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

标签 node.js postgresql sequelize.js sequelize-cli sequelize-typescript

我正在使用 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/

相关文章:

javascript - 使用Alexa和JS进行HTTP发布

node.js mongodb 检索 ISODate 格式

performance - 远程 PostgreSQL 访问

mysql - Sequelize JS - 如何使用组合键进行多个连接查询?

javascript - 通过 Nodejs 进行的 Handlebars 预编译在 Cloud9 上失败

sql - 选择一列上的最大运行总计小于给定值的行

postgresql - 如何在 PostgreSQL 数据库中找到靠在一起的点?

sequelize.js - 我怎么能在 sequelize 中编写这个查询?

javascript - 在 Sequelize 的 "where"子句中使用联结表中的列?

javascript - getmetadata 用于 Azure Blob 存储 NodeJ 中选择的 Blob