【问题标题】:Include inside include in sequelize包含在包含在续集中
【发布时间】:2020-06-30 13:11:55
【问题描述】:

基本上我有一个名为 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.js express sequelize.js


    【解决方案1】:

    您可以为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']],
    });
    

    【讨论】:

    • 你如何获得模型:用户工作?它根本不适合我,我必须使用字符串名称包括:['riotAccount']
    猜你喜欢
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2020-07-06
    • 1970-01-01
    • 2012-05-13
    • 2018-06-07
    相关资源
    最近更新 更多