mysql - sequelize 多个外键只包含一列

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

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

最佳答案

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

祝你好运! :)

关于mysql - sequelize 多个外键只包含一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459721/

相关文章:

php - 从 MySQL 中的序列化列中搜索数据

javascript - NodeJs 为每个循环并行运行

Java Prepared statement Sql查询错误

mysql - 未知变量 group_concat_max_len

javascript - ESLint 在 src 文件中寻找配置(以默认方式配置)

node.js - 无法使用 Node.js 在 heroku 上创建 postgresql 表

javascript - Node.js 全局变量和 TypeScript

postgresql - Sequelize 如何构建应用程序的聊天部分?

mysql - 如何在 Docker 中运行 Sequelize 迁移

javascript - 如何在 SequelizeJS 中创建模型时设置额外属性?