sequelize select and include another table alias
Asked Answered
B

1

24

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: 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)
   });

city Model

            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;
            };
Barrens answered 2/11, 2018 at 11:44 Comment(4)
Check the alias name buildings is same as defined or not , please post the City model code alsoReader
Oh I see now, that alias have to match with the model? If I change the alias in model, do I have to create a sequelize migration?Barrens
Nope , just change the name as it has , and Voila , you are good to goReader
Thanks a lot! it worked!Barrens
R
65

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

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

But in query , you are using buildings

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

It should be building :

include: [
   {
         model: Building, as: "building" // <---- HERE
   }
]
Reader answered 2/11, 2018 at 13:0 Comment(4)
@Barrens , Glad to know. Happy Coding BTW :)Reader
Why didn't sequelize team write this to it's documentation? interesting.Alley
I can only run this query once after starting the server. any subsequent query throws this error "You have used the alias company in two separate associations. Aliased associations must have unique aliases." any solution?Pandorapandour
Do you have city.addBuilding function? I am using alias when defining association. However add function is undefined.Mansfield

© 2022 - 2024 — McMap. All rights reserved.