gpt4 book ai didi

javascript - sequelize.js 中的自定义 json 响应

转载 作者:可可西里 更新时间:2023-11-01 07:26:06 25 4
gpt4 key购买 nike

我使用 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",
}

感谢您的帮助!

最佳答案

您可以向 Product 模型添加自定义 toJSON 方法:

instanceMethods: {
toJSON: function () {
var values = this.get();

if (this.Menu) {
values.icon = this.Menu.icon;
}

return values;
}
}

关于javascript - sequelize.js 中的自定义 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com