【问题标题】:sequelize select and include another table alias续集选择并包含另一个表别名
【发布时间】:2023-03-20 01:51:01
【问题描述】:

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

{ SequelizeEagerLoadingError: building 使用别名关联到城市。你已经 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;
            };

【问题讨论】:

  • 检查别名buildings是否与定义相同,请同时发布城市型号代码
  • 哦我明白了,别名必须与模型匹配?如果更改模型中的别名,是否必须创建 sequelize 迁移?
  • 不,只要改名字就行了,瞧,你很高兴
  • 非常感谢!成功了!

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


【解决方案1】:

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

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

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

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

应该是building

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

【讨论】:

  • @John ,很高兴知道。顺便说一句,快乐编码 :)
  • 为什么 sequelize 团队不把这个写到它的文档中?有趣。
猜你喜欢
  • 2018-10-18
  • 2016-06-21
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
相关资源
最近更新 更多