在另一个表中查找具有两条特定记录的记录 [英] Finding records with two specific records in another table

查看:31
本文介绍了在另一个表中查找具有两条特定记录的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Product 模型,has_and_belongs_to_many :taxons,我想找到特定分类单元中的所有产品.

I have a Product model that has_and_belongs_to_many :taxons, and I want to find all products that are in specific taxons.

例如,如果一个产品同时属于Ruby on Rails"和Shirts"分类群,我希望该产品在数据集中返回,但如果它只属于其中之一Ruby on Rails"或衬衫"

For example, if a product belongs to both the "Ruby on Rails" and "Shirts" taxon, I want that product to be returned in the dataset, but not if it only belongs to either "Ruby on Rails" or "Shirts"

推荐答案

不久前我遇到了这个问题,幸好有一个很好的解决方案.

I had this problem a while back, thankfully there is a nice solution.

def self.has_taxons(taxons)
  id = arel_table[:id]
  Product.joins(:taxons).where(taxons: { name: taxons }).group(id).having(id.count.eq(taxons.size))
end

这篇关于在另一个表中查找具有两条特定记录的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆