Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom json response in sequelize.js

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!

like image 581
Makromat Avatar asked Jan 05 '15 15:01

Makromat


1 Answers

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;
  }
}
like image 135
Jan Aagaard Meier Avatar answered Sep 30 '22 12:09

Jan Aagaard Meier