【问题标题】:Sequelize Aliases续集别名
【发布时间】:2019-10-09 20:04:32
【问题描述】:

我正在使用 sequelize,我有一个带有两个外键的模型

app.schemas.messengers.belongsTo(app.schemas.users, {
    foreignKey: 'id_user_to',
    as: 'to'
});

app.schemas.messengers.belongsTo(app.schemas.users, {
    foreignKey: 'id_user_from',
    as: 'from'
});

并且查询的结果必须返回这个特定用户的所有消息 这是查询的代码

 return Users.findAll({
     attributes: ['uuid', 'id', 'profile_pic', 'firstname', 'lastname', 'online'],
            where: whereUser,
            include: [{
                model: Messengers,
                as: 'from',
                // as: 'to',
                where: whereMessenger,
                $or: [{
                        id_user_to: user.id,
                    },
                    {
                        id_user_from: user.id

                    }
                ],
                order: [
                    ['createdAt', 'ASC'],
                ],
            }]
        })

但只返回给我写信的用户的消息,而不是给我写的用户的消息。 有什么办法可以让我在 sequelize 的 as 属性上放两个别名,还是有其他方法可以这样做?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    您必须包含两次,例如

       ...
       include: [
       {
          model: Messengers,
          as: 'from'                
          /* other stuff */
       },
       {
          model: Messengers,
          as: 'to'                
          /* other stuff */
       }
      ],
      ...
    

    另外,您的别名可能有问题,因为“to”和“from”是保留字。我推荐使用 msgTo 和 msgFrom...

    【讨论】:

    • tofrom 保留在哪里?这是 Sequelize 问题,还是其他问题?
    • @brad,保留在 SQL 中。例如,SELECT * FROM myTable As from 不起作用....
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2013-03-20
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多