5

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!

2 Answers 2

7

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;
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hello Jan Thanks for answer! I trying to add your solution but I have error : Possibly unhandled ReferenceError: menu is not defined
Sorry, I was a bit too quick - of course you have to actually access this.Menu after checking if it is defined
Thank you!!! Even next thing Can I remove menu child array somehow? Just have icon inside product array ?
delete values.Menu - This is just a plain javascript object we are working with :) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
This is outdated as of V4. You need to do Product.prototype.toJSON = function() {} docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html
-1

The product and The menu is a many-to-one associations. So Product.find() can't return the product array. Because the product corresponding to a menu.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.