如何通过两个外键将模型关联到另一个模型? (续集)

How to associate model to another model by two foreignKeys ? (in sequelize)

让我们想象一下情况

您有两个模型: event_user 具有属性:id event_user_message 具有属性:user_from_id、user_to_id

您想获得 20 event_user 与用户 X[=44= 联系(通过 message/s) ]

关联的定义

EventUser.hasMany(eventUserMessages, as: "from", foreignKey: "user_from_id")
EventUser.hasMany(eventUserMessages, as: "to", foreignKey: "user_to_id")

EventUserMessages.belongsTo(eventUser, as: "from", foreignKey: "user_from_id")
EventUserMessages.belongsTo(eventUser, as: "to", foreignKey: "user_to_id")

解决方案 1 问题在这种情况下,我只得到有两种对话方式的用户

var include, limit, where; 限制 = parameters.limit ? parameters.limit : 20;

include.push({
  model: models.eventUserMessages,
  as: "to",
  where: {user_from_id: parameters.inConnectionWith}
  attributes: []
});

include.push({
  model: models.eventUserMessages,
  as: "from",
  where: {user_to_id: parameters.inConnectionWith}
  attributes: []
});

eventUserModel.findAll({
  include: include,
  where: where
})

解决方案 2 在此解决方案中,您将获得所有预期结果 问题在此解决方案中您不能使用限制(不起作用)

include.push({
  model: models.eventUserMessages,
  as: "to",
  required: false,
  attributes: []
});

include.push({
  model: models.eventUserMessages,
  as: "from",
  required: false,
  attributes: []
});

where = Sequelize.and(where, Sequelize.or({
  "to.user_from_id": parameters.inConnectionWith
}, {
  "from.user_to_id": parameters.inConnectionWith
}));

eventUserModel.findAll({
  include: include,
  where: where
})

如果您提供一些有关如何实现此目标的建议,我们将不胜感激

提前致谢

你把自己弄糊涂了。在您的第一个解决方案中,通过执行:

include.push({
  model: models.eventUserMessages,
  as: "to",
  where: {user_from_id: parameters.inConnectionWith}
  attributes: []
});

您实际上是在 EventUser.id = EventUserMessages.user_to_id WHERE EventUserMessages.user_from_id = parameters.inConnectionWith 上进行连接。

联接已将您的结果集缩减为包含 user_to_id = parameters.inConnectionWith 的结果集。然后,您的 where 标准将结果进一步缩减为 user_to_id = parameters.inConnectionWith

这为您提供了通过 2 种沟通方式返回用户的结果。如果你不明白为什么,请看下面我的回答:

include.push({
  model: models.eventUserMessages,
  as: "to",

  //firstly, you don't need this.
  //Secondly, if anything, it should be user_to_id, which won't do anything.
  /* where: {user_to_id: parameters.inConnectionWith} */ 

  attributes: []
});

但是,如果您的数据集不需要 event_user table 中的属性,则在这种情况下不需要使用 include。把它们去掉,你的解决方案 1 应该可以正常工作。

运行 下面建议的查询效率更高:

EventUserMessages.findAll({
    where: Sequelize.or(
        { user_from_id: parameters.inConnectionWith },
        { user_to_id: parameters.inConnectionWith }
    },
    limit: 20,
    order: [ you need to order them so you will return the relevant 20 datasets ]
});