Rails - 查询 has_many 关联

4

我在查询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

我想查询只销售衬衫的商店。因此,我需要一个查询,返回id3store记录。

当我尝试执行以下操作时:

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

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


请提供您的查询预期结果,因为问题不太清楚。 - Moamen Naanou
1
预期结果是具有ID 3(Dillards)的商店记录,因为这是唯一只销售衬衫的商店。 #<商店 id: 3, 名称: "Dillards"> - Alex
4个回答

2
我最终使用了以下内容:
Store.joins(:items).group('items.store_id').having("max(items.name) = 
  min(items.name) and min(items.name) = 'shirt'")

1
Store.includes(:items)
  .where(items: { name: 'shirt' })
  .where.not(id:
    Item.where.not(name: 'shirt').select(:store_id)
  )

希望有更好的方法...(如果有人知道)。

1
在你的Item模型中,你需要设置counter_cache属性:
belongs_to :store, counter_cache: true

然后您的查询将是:

(保留HTML,不解释)。

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

0

在帖子中提到的一种只存储衬衫这样的物品的方法是:

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

希望能对你有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接