具有计数查询条件的 ActiveRecord

ActiveRecord having count query condition

我有 2 个模型:ConversationMessage 我需要检索属于 Brand 的所有对话,其中至少有一条来自品牌的消息和一条来自有影响力的消息

这是我的查询:

Conversation.includes(:messages)
            .joins(:messages)
            .group("conversations.id, messages.id")
            .where("conversations.brand_id = ?", brand_id)           
            .having("COUNT(messages.authorable_type = 'Influencer') > 0 AND COUNT(messages.authorable_type = 'BrandMember') > 0")
            .limit(10)

但是我得到的对话没有来自两者的消息...请问我做错了什么?

问题出在 COUNT 表达式上。

请注意,COUNT 计算所有 NON-NULL 值。在您的情况下,您将 COUNT 一些条件表达式计算为 TRUEFALSE 而不是 NULL.

最懒惰的解决方案如下所示:

COUNT(messages.authorable_type = 'Influencer' OR NULL)