sequelize多个外键只包含一列

时间:2017-08-02 11:32:34

标签: mysql node.js sequelize.js

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

`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']}] })

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

1 个答案:

答案 0 :(得分:3)

尝试为关联设置名称,以便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来访问该关联。

祝你好运! :)