Sequelize多对多关联查询如何格式化结果,将中间表字段平铺到关联对象中
Sequelize多对多关联中间表字段平铺解决方案
你使用的是Sequelize ORM进行多对多关联查询,默认配置下中间表的字段会嵌套在关联名对应的子对象中,要实现平铺可以通过两种方式实现:
方案1:查询后手动格式化(兼容性最好,无额外配置要求)
拿到查询结果后手动遍历产品列表,将中间表字段合并到外层对象即可,不需要修改查询逻辑:
async getOrder(req, res) { const { id } = req.params; const order = await Orders.findByPk(id, { include: [{ association: 'products', attributes: ['name'], through: { attributes: ['quantity', 'price'], } }] }) if (!order) return res.status(404).send({ message: `order ${id}` }) // 格式化产品字段 const result = order.toJSON(); result.products = result.products.map(item => { return { name: item.name, quantity: item.OrdersProducts.quantity, price: item.OrdersProducts.price } }) return res.json(result); },
方案2:查询时直接映射字段(不需要额外处理返回结果)
通过Sequelize的字段别名功能,直接将中间表字段映射到外层属性,同时关闭嵌套中间表对象的返回:
// 需先引入你项目中初始化的Sequelize实例,示例:const sequelize = require('./config/sequelize') async getOrder(req, res) { const { id } = req.params; const order = await Orders.findByPk(id, { include: [{ association: 'products', attributes: [ 'name', // 把中间表字段映射到产品对象外层 [sequelize.col('OrdersProducts.quantity'), 'quantity'], [sequelize.col('OrdersProducts.price'), 'price'] ], through: { attributes: [] // 不返回嵌套的中间表对象 } }], raw: true, nest: true }) if (!order) return res.status(404).send({ message: `order ${id}` }) return res.json(order); },
注意:方案2中的
OrdersProducts需要替换为你实际的中间表模型名
内容的提问来源于stack exchange,提问作者Matheus Martins
相关产品推荐
相关产品推荐

