我有两个模型,对话和电话,两者都有彼此。电话可以有很多对话,对话可以有很多电话(两个或更多)。
class Conversation < ActiveRecord::Base
has_and_belongs_to_many :phones
end
class Phone < ActiveRecord::Base
has_and_belongs_to_many :conversations
end
当然,还有一个 conversations_phones 连接表。
如果我有两个或更多电话对象,我如何找到它们共享的所有对话的列表?问题:对话不能包含任何其他电话(即电话 ID 的数量等于我们搜索的号码)。
我已经能够使用纯 Rails 做到这一点,但它涉及循环每个对话并依靠数据库。不好。
我不介意做纯 SQL;使用模型 ID 应该有助于阻止注入攻击。
我最接近的是:
SELECT conversations.* FROM conversations
INNER JOIN conversations_phones AS t0_r0 ON conversations.id = t0_r0.conversation_id
INNER JOIN conversations_phones AS t0_r1 ON conversations.id = t0_r1.conversation_id
WHERE (t0_r0.phone_id = ? AND t0_r1.phone_id = ?), @phone_from.id, @phone_to.id
但它包括与外部电话的对话。我有一种感觉 GROUP BY 和 HAVING COUNT 会有所帮助,我对 SQL 太陌生了。