简体   繁体   中英

How can I get value from sequelize associated model?

I still trying to get menu_title from associated Menu model to json. If I use below described code console shows me error ER_BAD_FIELD_ERROR: Unknown column 'Products.MenuId' in 'field list' also if I have defined {foreignKey: 'menu_id'} . What I'm doing wrong?

Menu model:

module.exports = function(sequelize, Sequelize) {
  var Menu = sequelize.define("Menu", {
      owner_id: Sequelize.INTEGER,
      menu_title: Sequelize.STRING,
  }, {
      classMethods: {
        associate: function(models) {
          Menu.hasMany(models.Product)
        }
      }
  });
  return Menu;
};

Product model:

module.exports = function(sequelize, Sequelize) {
  var Product = sequelize.define("Product", {
      owner_id: Sequelize.INTEGER,
      menu_id: Sequelize.INTEGER,
      product_title: Sequelize.STRING,
  }, {
      classMethods: {
        associate: function(models) {
          Product.belongsTo(models.Menu, { foreignKey: 'menu_id'})
        }
      }
  });
  return Product;
};

Then inside controller:

Menu.find({
    where: { owner_id: req.user.id },
    include: [
        { model: Product }
    ]
}).success(function(match) {
    res.json(match.home);
});

Thanks for any help!

You need to include the foreign key on both sides of the relation

Menu.hasMany(models.Product, { foreignKey: 'menu_id'})

Otherwise sequelize assumes that the foreign key is called menuId when querying from the menu side of the relation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM