You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize中如何在findByPk语句中同时使用include和attributes参数

问题原因

Sequelize的findByPk方法仅接收2个参数:第一个是要查询的主键值,第二个是唯一的查询配置对象。你之前将include和attributes拆成两个独立的对象作为第二、第三个参数传入,第三个参数会被Sequelize直接忽略,因此两个配置永远只能生效一个。

修正方案

将include和attributes配置合并到同一个配置对象中即可,修正后的代码如下:

exports.findOne = (req, res) => {
  var id = req.params.id;

  User.findByPk(id, {
    include: ["roles"],
    attributes: {
      exclude: ['password']
    }
  })
    .then(data => {
      res.send({"data": data, "resultCode": 1, "message": ""});
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving users."
      });
    });
}

可选优化

如果你不需要关联查询返回的user_roles中间表字段,可以调整include配置将其过滤:

include: [{
  association: "roles",
  through: { attributes: [] }
}]

内容的提问来源于stack exchange,提问作者cauchuyennhocuatoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:06:03