微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关联的 ActiveRecord / Arel 链条件

如何解决关联的 ActiveRecord / Arel 链条件

我正在尝试构建一个查询,该查询根据关联条件选择记录。 在我的示例中,我有 Box has_many ItemsItem belong_to Box

我想获得所有包含 Boxesitems,条件如下:

(item.type = "toy" and item.used_count >= 2) AND
(item.type = "book" and item.used_count >= 3) AND
(item.type = "bottle" and item.used_count >= 3)

我尝试过使用 Arel,但似乎无法正确使用。我只能设法找到具有单一条件的盒子,但无法将它们链接起来。 有人可以帮我构建这个查询吗?我花了太长时间,还没有在其他 SO 问题中找到任何我可以适应的解决方案。

解决方法

如果你想在 Rails 中写这个条件,你可以使用 where("SQL directly here")

像这样:

Box.joins(:items).where("(items.type = 'toy' and items.used_count >= 2) AND (items.type = 'book' and items.used_count >= 3) AND (items.type = 'bottle' and items.used_count >= 3)")

注意表示表格或关联名称的复数形式

但是我认为这不是您想要的

您想要获得具有 3 个不同项目条件的盒子,其中第一个条件(类型=玩具和已用_计数>=2)和另一个项目(类型=书和已用_计数>=3)和另一个_项目(类型=瓶子和已使用_计数) >=3)

您可能需要在这里自定义联接

Box.joins("JOIN items item1 ON item1.box_id = box.id AND item1.type = 'toy' and item1.user_count >= 2").joins("JOIN items item2 ON item2.box_id = box.id AND item2.type = 'book' and item2.user_count >= 3").joins("JOIN items item3 ON item3.box_id = box.id AND item2.type = 'bottle' and item3.user_count >= 3")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。