顺序选择并包含另一个表别名 [英] sequelize select and include another table alias

查看:189
本文介绍了顺序选择并包含另一个表别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using sequelize to acess a postgres database and I want to query for a city and for example include the "Building" table but I want to rename the output to "buildings" and return the http response but I have this error:

{SequelizeEagerLoadingError:建筑使用别名与城市相关联.你 e包含一个别名(建筑物),但与您的a中定义的别名不匹配 联系.

{ 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:

As you have defined alias name in below code is building :

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

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

But in query , you are using buildings

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


应为building:

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

这篇关于顺序选择并包含另一个表别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆