I using sequelize for getting json from mysql db. So I have two models Menu and Product further associations like:
Menu.js
  classMethods: {
    associate: function(models) {
      Menu.hasMany(models.Product, {foreignKey: 'menu_id'})
    }
  }
Product.js
  classMethods: {
    associate: function(models) {
      Product.belongsTo(models.Menu, {foreignKey: 'menu_id'})
    }
  },
  // IF I ADD BELOW CODE I HAVE ERROR: Possibly unhandled ReferenceError: menu is not defined
  instanceMethods: {
     toJSON: function () {
       var values = this.get();
       if (this.Menu) {
         values.icon = menu.icon;
       }
       return values;
     }
   }
and
 Product.findAll({
      where: { /* id: */ },
      include: [
          { model: Menu }
      ]
  }).success(function(match) {
    res.json(match);
 });
Then I get:
{
  "id": 3,
  "menu_id": 1,
  "product_title": "whatever",
  "price": 22,
  "createdAt": "0000-00-00 00:00:00",
  "updatedAt": "0000-00-00 00:00:00",
  "Menu": {
    "id": 1,
    "menu_title": "whatever",
    "icon": "someurlforicon",
    "createdAt": "2014-12-29T00:00:00.000Z",
    "updatedAt": "2014-12-29T00:00:00.000Z"
  }
}
Is possible to just extend products array with icon from menu model ? LIKE:
{
  "id": 3,
  "menu_id": 1,
  "product_title": "whatever",
  "price": 22,
  "icon": "someurlforicon",
  "createdAt": "0000-00-00 00:00:00",
  "updatedAt": "0000-00-00 00:00:00",
}
Thanks for any help!
You could add a custom toJSON method to the Product model:
instanceMethods: {
  toJSON: function () {
    var values = this.get();
    if (this.Menu) {
      values.icon = this.Menu.icon;
    }
    return values;
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With