我想更改 orm 查询返回的数据结构。总共有四张桌子。product,category是多对多的关系,有一个product_category表作为桥梁,一共有四个表,包括department表。关联如下:
// product
product.belongsToMany(models.category, {
through: 'product_category',
foreignKey: 'product_id'
});
// product_category
product_category.belongsTo(models.product, {
foreignKey: 'product_id'
});
product_category.belongsTo(models.category, {
foreignKey: 'category_id'
});
// category
category.belongsToMany(models.product, {
through: 'product_category',
foreignKey: 'category_id'
});
category.belongsTo(models.department, {
foreignKey: 'department_id'
});
// department
department.hasMany(models.category, {
foreignKey: 'department_id'
});
通过上面的表结构,得到如下查询,得到对应的产品department_id:
const query = await product.findOne({
where: { product_id: id },
include: {
model: category,
attributes: ['category_id', ['name', 'category_name']],
include: {
model: department,
attributes: ['department_id', ['name', 'department_name']]
}
},
attributes: []
});
const data = query.categories;
生成的json数据如下:
"data": [
{
"category_id": 1,
"category_name": "French",
"department": {
"department_id": 1,
"department_name": "Regional"
},
"product_category": {
"product_id": 1,
"category_id": 1
}
}
]
我想让上面的数据如下:
"data": [
{
"category_id": 1,
"category_name": "French",
"department_id": 1,
"department_name": "Regional"
}
]
为了如上处理数据,有两种方式可以修改基于sql的orm查询和product在javascript中处理值。不过由于我是用orm学的sql,不知道第一种方法,所以决定用它作为第二种方法。
明月笑刀无情
相关分类