Rails-获取具有重复项的对象 [英] Rails - get objects of objects WITH duplicates
问题描述
在解决我需要获取一次查询中来自对象的对象。
这是该问题的后续措施。我选择为此创建一个新问题,因为根据我以前的规范回答了最后一个问题。
This is a follow up to that question. I chose to create a new question to this since the last one was answered according to my previous specification. Please do refer to that previous question for details.
基本上,我想在一个查询中获取多个对象的所有对象。例如。如果某个产品具有多个类别,而该类别又具有多个产品,那么我想获得该关系中的所有产品,并且更容易(且错误地)放入:
Basically, I wanted to get all the objects of multiple objects in one single query. E.g. if a Product has several Categories which in turn has several Products, I want to get all the Products in that relation, easier (and erronously) put:
all_products = @my_product.categories.products
此查询已解决。我想(最好是)更改此查询:
This was solved with this query. It is this query I would (preferably) like to alter:
Product.includes(:categories).where(categories: { id: @my_product.categories.pluck(:id) } )
现在,我意识到我错过了一些东西使用此解决方案的原因是,我仅获得一份独特的产品列表(也可以期望得到)。但是,我想也获取可能重复的列表。
Now, I realized something I missed using this solution was that I only get a list of unique Products (which one would expect as well). I would however like to get a list with possible duplicates as well.
基本上,如果类别中包括蓝色电动车 (蓝色,电动和汽车)我想返回该对象的三个实例,而不是一个唯一的实例。
Basically, if a "Blue, Electric Car" is included in categories ("Blue", "Electric" and "Car") I would like to get three instances of that object returned, instead of one unique.
我想这不是使Rails感觉,但有没有办法改变上面的查询,以便它不为我提供返回列表中唯一对象的列表,而是完整列表?
I guess this does not make Rails-sense but is there a way to alter the query above so that it does not serve me a list of unique objects in the returned list but rather the "complete" list?
推荐答案
由于要重复,只需将 includes
更改为 joins
, (我刚刚对此进行了测试)。 joins
本质上将合并(内部联接)这两个表,从而为您提供一个唯一的记录列表(按产品和类别)。 includes
确实渴望加载,它只是已经加载了关联的表,但是进行了外部联接,因此,检索到的记录也是唯一的(但仅针对每个Product)。
Since you want duplicates, just change includes
to joins
, (I tested this just now). joins
will essentially combine (inner-join) the two tables giving you a list of records that are all unique (per Product and Category). includes
does eager loading which just loads the associated tables already but does an outer-join, and therefore, the retrieved records are also unique (but only per Product).
Product.joins(:categories).where(categories: { id: @my_product.categories.pluck(:id) } )
这篇关于Rails-获取具有重复项的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!