【问题标题】:ActiveRecord / Arel chain conditions on associationActiveRecord / Arel 链上的关联条件
【发布时间】:2021-04-10 14:10:25
【问题描述】:

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

我想获取所有包含itemsBoxes,条件如下:

(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 问题中没有找到任何我可以适应的解决方案。

【问题讨论】:

  • 你是如何链接他们的?
  • 你确定要OR他们一起吗?
  • 是的,我可能确实需要使用OR,只是不知道该怎么做。这正是我的问题:(

标签: ruby-on-rails activerecord arel


【解决方案1】:

如果你想在 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 个不同项目条件的盒子,第一个条件(type=toy 和 used_count>=2)和另一个项目(type=book 和 used_count>=3)和另一个项目(type=bottle 和 used_count >=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")

【讨论】:

    猜你喜欢
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多