我想更改 orm 查询返回的数据结构。总共有四张桌子。product,category是多对多的关系,有一个product_category表作为桥梁,一共有四个表,包括department表。关联如下:// productproduct.belongsToMany(models.category, { through: 'product_category', foreignKey: 'product_id'});// product_categoryproduct_category.belongsTo(models.product, { foreignKey: 'product_id'});product_category.belongsTo(models.category, { foreignKey: 'category_id'});// categorycategory.belongsToMany(models.product, { through: 'product_category', foreignKey: 'category_id'});category.belongsTo(models.department, { foreignKey: 'department_id'});// departmentdepartment.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,不知道第一种方法,所以决定用它作为第二种方法。
1 回答
明月笑刀无情
TA贡献1828条经验 获得超4个赞
我以一种微不足道的方式实现了它。它看起来像一个完整的胃。如果另一个人将最佳方式放入答案中,那就太好了。
const getProduct = () => {
const a = query.categories[0];
const b = a.get({ plain: true });
const { category_id, category_name } = b;
const { department_id, department_name } = b.department;
return {
category_id,
category_name,
department_id,
department_name
};
};
ctx.body = getProduct();
Json数据输出:
"product": {
"category_id": 1,
"category_name": "French",
"department_id": 1,
"department_name": "Regional"
}
sequelize 查询将像dataValues: {}, (...)运行console.log (). 如果您这样做,您将无法处理您的数据。所以在包含查询的变量之后处理数据是关键点,如下所示:
data.get ({plain: true})
添加回答
举报
0/150
提交
取消