【问题标题】:sequelize multiple foreign key includes only one columnsequelize 多个外键只包含一列
【发布时间】:2023-03-31 11:54:01
【问题描述】:

我从用户表中创建了两个外键。

db.Subscription.belongsTo(db.User, {foreignKey: 'creatorId'});
db.Subscription.belongsTo(db.User, {foreignKey: 'subscriberId'});

在搜索查询期间,我得到 subscriberId 列而不是 creatorId

Subscription.findAll({
    where: {
      subscriberId: req.decoded._id
    },
    include: [
      {
          model: User, 
          foreignKey: 'creatorId', 
          attributes: ['name', 'role', 'uid', 'imageUrl']
      }
    ]
})

有人可以找出我在这里做错了什么。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    尝试为关联设置名称,以便 Sequelize 更好地了解要包含的关联。您可以这样做来设置关联的名称...

    db.Subscription.belongsTo(db.User, {
      as: 'creator',
      foreignKey: 'creatorId'
    });
    
    db.Subscription.belongsTo(db.User, {
      as: 'subscriber',
      foreignKey: 'subscriberId'
    });
    

    然后你可以在查询中使用这些名称来获取特定的关联,这样......

    Subscription.findAll({
      include: {
        model: User,
        as: 'creator',
        attributes: ['name', 'role', 'uid', 'imageUrl']
      },
      where: {
        subscriberId: req.decoded._identer
      }
    });
    

    当您多次关联到同一个表时,设置名称有助于 ORM 确定要加载哪个关联。作为记录,对于返回的所有记录,您可以通过访问实例上的 .creator 来访问该关联。

    祝你好运! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      相关资源
      最近更新 更多