Express.js API中用Sequelize实现三表关联并按restaurant_type_id过滤分店
问题原因
你的代码错误将过滤条件赋值给了关联查询的type参数(该参数仅用于指定JOIN连接类型,如内连接、左连接),没有真正传递给Restaurant模型的查询条件,因此过滤逻辑完全不生效。
修正后代码
const findAll = async (req, res) => { const restaurantTypeId = req.query.restaurantType ? parseInt(req.query.restaurantType) : null; // 定义Restaurant模型的过滤条件,避免和关联type参数重名 const restaurantWhere = restaurantTypeId ? { restaurantTypeId: restaurantTypeId } : null; try { const restaurantBranches = await RestaurantBranch.findAll({ order: [['id', 'ASC']], include: [ { model: Restaurant, where: restaurantWhere, // 正确传递过滤条件 required: true, // 强制内连接,自动过滤不符合餐厅类型的分店 include: [{ model: RestaurantType }] } ] }); return res.status(200).send({ message: "restaurant branches returned", data: restaurantBranches }); } catch (error) { res.status(500).send(error.message); } } module.exports = { findAll }
修改说明
- 调整过滤条件变量名,避免和关联查询的
type参数重名导致语义混淆 - 把餐厅类型过滤条件正确绑定到Restaurant关联配置的
where属性上 - 新增
required: true强制使用内连接查询,确保只有匹配到对应类型餐厅的分店才会返回,无需额外做数据过滤 - 保留了你原有排序、关联返回RestaurantType数据的逻辑,不影响原有返回结构
- 统一用
async/await的异常捕获写法,避免混合使用then/catch导致逻辑混乱
内容的提问来源于stack exchange,提问作者Exodus Reed
相关产品推荐
相关产品推荐

