【问题标题】:Getting associated objects count with condition in Rails在 Rails 中根据条件获取关联对象计数
【发布时间】:2020-01-07 06:18:17
【问题描述】:

我有以下型号的 Merchant、Offer 和 GiftCards。我想在特定条件下获得所有相关的优惠和gift_cards。

它们之间的关联:

商人.rb

has_many :offers
has_many :gift_cards

gift_card.rb:

belongs_to :merchant

offer.rb:

belongs_to :merchant

要直接获得计数,我可以做到

Merchant.pluck(
    :id, Arel.sql('COUNT(offers.id)'), Arel.sql('MAX(offers.id)'),
     Arel.sql('COUNT(gift_cards.id)'), Arel.sql('MAX(gift_cards.id)')
 )

但问题陈述是我有一个符合条件的_offer_ids 和符合条件的_gift_card_ids 的数组。我想获取商家的合格优惠/合格礼品卡计数。

我可以执行类似于以下代码的操作来获取计数。

merchant.offer_ids & eligible_offer_ids

但是有没有办法修改查询以获取合格的优惠而不是商家中的所有优惠。

类似于下面的查询。

    Merchant.pluck(
    :id, Arel.sql('COUNT(eligible_offer_ids.id)'), Arel.sql('MAX(eligible_offer_ids.id)'),
     Arel.sql('COUNT(eligible_gift_card_ids.id)'), 
     Arel.sql('MAX(gift_eligible_gift_card_id.id)')
 )

【问题讨论】:

  • 你能粘贴模型/关系吗?

标签: sql ruby-on-rails associations


【解决方案1】:
Merchant.joins(:offers, :gift_cards)
  .select('merchants.id, COUNT(gift_cards) as offer_count, 
           COUNT(gift_cards) as gift_card_count')
  .where(offers: { id: eligible_offer_ids }, 
         gift_cards: { id: eligible_gift_cards_ids })
  .group(:id)

这将返回商家 ID、offer_counts 和 gift_card_counts 的 ActiveRecord_Relation,其中符合条件的优惠和礼品卡 ID 在这些数组中。然后,您可以遍历所需的任何内容:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多