在sequelize.js中自定义json响应

我使用sequelize从MySQL数据库获取JSON。 所以我有两个模型MenuProduct进一步的关联,如:

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

  Product.findAll({ where: { /* id: */ }, include: [ { model: Menu } ] }).success(function(match) { res.json(match); }); 

然后我得到:

 { "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" } } 

有可能只是从菜单模型扩展产品数组图标? 喜欢:

 { "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", } 

谢谢你的帮助!

您可以将自定义toJSON方法添加到产品模型中:

 instanceMethods: { toJSON: function () { var values = this.get(); if (this.Menu) { values.icon = this.Menu.icon; } return values; } } 

该产品和菜单是多对一的关联。 所以Product.find()不能返回产品数组。 因为产品对应一个菜单。