我有两张桌子:Conversations
和ConversationParticipants
。
我需要获取用户1
和2
都参与的对话列表。
在MySQL
中,查询将是:
SELECT conversation_participants.conversation_id FROM conversation_participants
JOIN conversations t1
ON t1.conversation_id = conversation_participants.conversation_id
AND conversation_participants.user_id = 11
JOIN conversation_participants t2
ON t1.conversation_id = t2.conversation_id
AND t2.user_id = 2
然而,在Sequelize中我无法理解如何设置模型关系以便我可以进行单个查询。我尝试了这个没有成功(请注意,这几乎是伪代码,为了清楚起见这样报告):
var Conversation = sequelize.define('conversations', {
conversationId: Sequelize.INTEGER.UNSIGNED,
});
var ConversationParticipant = sequelize.define('conversation_participants', {
participationId: Sequelize.INTEGER.UNSIGNED,
userId: Sequelize.INTEGER.UNSIGNED,
conversationId : Sequelize.INTEGER.UNSIGNED,
});
Conversation.hasMany(ConversationParticipant, { as : 'Participants'});
然后
ConversationParticipant.findAll({
where : { userId : 1 },
include : [{
model : Conversation,
as : 'conversation',
include : [{
model : ConversationParticipant,
as : 'Participants',
where : { userId : 2 }
}]
}]
我收到以下错误:
Error: conversation_participants is not associated with conversations!
。
有什么想法吗?
答案 0 :(得分:0)
您可以采用的一种方法是找到参与者拥有用户1或2的对话,然后过滤包含这两者的对话:
<g id="Artwork_18" class="cerebellum">
<defs><path id="SVGID_1_" d="M1097.44 638.07l4.77-53.1 53.5 4.8-4.77 53.1z"/></defs>
<clipPath id="SVGID_2_">
<use xlink:href="#SVGID_1_" overflow="visible"/>
</clipPath>
<path d="M1114.7 586l-13 5.2-1.9 21.2z" class="st1 poly"/> <!-- ... more paths... --> </g>
答案 1 :(得分:0)
您缺少ConversationParticipant
定义中的belongsTo关联。 Sequelize模型需要显式关联,因为您尝试通过Conversation
实例访问ConversationParticipant
,即使关联Conversation
不是ConversationParticipant
。
除了hasMany关联之外还有这样的东西:
ConversationParticipant.belongsTo(Conversation, { as : 'conversation',
foreignKey: 'conversationId', targetKey: 'conversationId'});
然后从conversationId
模型中移除ConversationParticipant
字段定义,因为belongsTo
也会为您创建。{/ p>