繁体   English   中英

如何使用 SQL/ActiveRecord 查询字段的非唯一值的关联?

[英]How do I query an association for non-unique values of a field with SQL/ActiveRecord?

老实说,我什至不知道如何用一句话来描述它,所以这个标题可能会离题。 这是我正在尝试做的事情:

我有一个相当简单的 model。 用户 -> 故事 -> 评论。 也就是说,一个用户有_many Stories,一个Story has_many Comments。

我要做的只是返回以下故事:

  • 有意见
  • 由当前用户创建或已由 current_user 评论
  • 但如果当前用户是唯一对其发表评论的用户,则不会

到目前为止,我所拥有的是:

Story.includes(:comments).where("stories.user_id = ? OR comments.user_id = ?", current_user.id, current_user.id)

但我不知道如何做 SQL 中的最后一个条件。 我唯一能做的就是使用 Enumerable 方法。

@stories.reject! { |story| story.comments.collect(&:user_id).all? { |user_id| user_id == current_user.id }}

听起来你想要一个嵌套的子查询,比如

Story.includes(:comments).where("stories.user_id = ? OR comments.user_id = ?) 
    and exists (select 'x' from comments c2 where c2.story_id = stories.id 
    and c2.user_id != ?)",
  current_user.id, current_user.id, current_user.id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM