rails-query有很多关联

olmpazwi  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(291)

我很难查询一个有很多关联的。上下文是存储。

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 记录 id3 .
当我试着

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

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

gzjq41n4

gzjq41n41#

在你的 Item 模特,你需要设置 counter_cache :

belongs_to :store, counter_cache: true

那么您的查询将是:

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

wd2eg0qa2#

最后我用了:

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

mbzjlibv3#

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

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

px9o7tmv

px9o7tmv4#

正如帖子中所提到的,只有衬衫这样的商品才会出现:

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

希望有帮助!!

相关问题