【问题标题】:Rails - query a has_many associationRails - 查询 has_many 关联
【发布时间】:2018-05-23 21:11:28
【问题描述】:

我在查询 has_many 关联时遇到问题。上下文是商店。

class Store < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to: store
end

存储表:

id  name
1   Macys
2   Target
3   Dillards

物品表:

id  store_id    name
1   1           pants
2   1           shirt
3   2           pants
4   2           shirt
5   3           shirt

我正在尝试查询只销售衬衫的商店。所以我需要一个返回store 记录的查询,其中id 为3。

当我尝试这样做时

Store.includes(:items).where(
  items: { name: %w(shirts)} ).references(:items)

它返回 store_ids 1、2 和 3(所有商店),因为它们都有衬衫。

【问题讨论】:

  • 由于问题不清楚,请提供您查询的预期结果。
  • 预期结果是 ID 为 3 (Dillards) 的商店记录,因为那是唯一一家只销售衬衫的商店。 #&lt;Store id: 3, name: "Dillards"&gt;

标签: mysql ruby-on-rails activerecord associations has-many


【解决方案1】:

我最终使用了:

Store.joins(:items).group('items.store_id').having("max(items.name) = 
  min(items.name) and min(items.name) = 'shirt'")

【讨论】:

    【解决方案2】:
    Store.includes(:items)
      .where(items: { name: 'shirt' })
      .where.not(id:
        Item.where.not(name: 'shirt').select(:store_id)
      )
    

    希望有更好的方法...(如果有人的话)

    【讨论】:

      【解决方案3】:

      在您的Item 模型中,您需要设置counter_cache:

      belongs_to :store, counter_cache: true
      

      那么您的查询将是:

      Store.joins(:items).where('items_count = ? AND items.name = ?', 1, 'shirt')
      

      【讨论】:

        【解决方案4】:

        在帖子中提到的一种方法是:商店仅将商品作为衬衫:

        Store.joins(:item).where("items.name = ?", 'shirt').where.not(item_name: Item.where("items.name != ?", "shirt"))
        

        希望对你有帮助!!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多