首页 > 解决方案 > 包含在包含在续集中

问题描述

基本上我有一个名为 UserLadder 的模型,其中包括另一个名为 User 的模型:

  try {
    const leaderboard = await UserLadder.findAll({
      where: {
        weeklyLadderId: req.params.id,
      },
      limit: req.params.playersNumber,
      attributes: ['userPoints'],
      include: [{ model: User, attributes: ['displayName', 'profilePicture'] }],
      order: [['userPoints', 'DESC']],
    });

    res.json(leaderboard);
  } catch (error) {
    console.error(error);
    res.status(500).send('Server Error.');
  }

结果:

[
    {
        "userPoints": 132.5,
        "user": {
            "displayName": "Ervin Howell",
            "profilePicture": "https://banner2.cleanpng.com/20180926/igw/kisspng-league-of-legends-esports-logo-font-game-v-v-pls173-5bab06e810b838.0162687215379350800685.jpg"
        }
    },
    {
        "userPoints": 0,
        "user": {
            "displayName": "Leanne Graham",
            "profilePicture": "https://banner2.cleanpng.com/20180926/igw/kisspng-league-of-legends-esports-logo-font-game-v-v-pls173-5bab06e810b838.0162687215379350800685.jpg"
        }
    }
]

但是这个用户模型与另一个名为 RiotAccount 的模型有关系,我试图弄清楚如何让第三个模型的数据随用户一起提供,因为我在 json 响应中需要它。

标签: node.jsexpresssequelize.js

解决方案


您可以为模型添加“内部”包含,User如下所示:

const leaderboard = await UserLadder.findAll({
  where: {
    weeklyLadderId: req.params.id,
  },
  limit: req.params.playersNumber,
  attributes: ['userPoints'],
  include: [{
    model: User,
    include: [{
      model: RiotAccount, attributes: [...]
    }]
    attributes: ['displayName', 'profilePicture'] 
  }],
  order: [['userPoints', 'DESC']],
});

推荐阅读