【问题标题】:Sequelize include is not working with hasOne relationshipSequelize include 不适用于 hasOne 关系
【发布时间】:2021-03-07 08:01:11
【问题描述】:

您好,我有一个User 模型和一个ProfilePicture 模型。用户只能拥有一张头像,一张头像只能属于一个用户。

我的问题是在我的获取请求中,我正在调用个人资料图片模型并包括用户模型,我只获得了我的个人资料图片而没有我的用户对象。

User.hasOne(pp,
    { foreignKey: "userId" }
);

pp.belongsTo(User,
    { foreignKey: "userId" }
);

router.get(
    "/pp",
    auth,
    async (req, res) => {
        let { id } = req.user;

        await pp.findOne({
            where: {
                userId: id
            }
        },
        {
            include: [{
                model: User,
            }]
        }).then((user) => {
            console.log(user)
                
            if (!user)
                return res.status(404).send();

            res.send(user);
        });
    });

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    您需要在第一个参数中包含include

    await pp.findOne({
      where: {
        userId: id
      },
      include: [
        {
          model: User
        }
      ]
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多