基于两个相关联的记录的查询 [英] Querying based on two associated records

查看:155
本文介绍了基于两个相关联的记录的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了很多变种的产物,这些变体具有两个属性:大小和颜色
我想查询基于两个属性,我传递的变种 - 我得到了它具有以下工作:

I have a product that has many variants, those variants have two attributes: Size and Color.
I want to query for the Variant based on the two attributes I pass in - I got it to work with following:

variants = Spree::Variant.joins(:option_values).where(:spree_option_values => {:id => size.id}, :product_id => prod.id).joins(:option_values)

variant = variants.select{|v| v.option_values.include?(size)}

这是我的理解,选择的方法更多的还是通过数组,这是有点慢较少迭代。我宁愿有发现直接根据这两个属性变量的查询。
我试过如下:

From my understanding, the select method more or less iterates through the array, which is kinda slow. I would rather have a query that finds the variant directly based on those two attributes.
I tried the following:

Spree::Variant.joins(:option_values).where(:spree_option_values => {:id => size.id}, :product_id => prod.id).joins(:option_values).where(:spree_option_values => {:id => color.id})

但这只结束了在返回一个空数组。
我怎么会去吗?

but this only ended up in returning an empty array.
How would I go about this?

编辑:下面是产品,变型和option_values​​型号:

Here are the product, variant and option_values models:

产品: 的https://github.com/s$p$pe/s$p$pe/blob/master/core/app/models/s$p$pe/product.rb

词: 的https://github.com/s$p$pe/s$p$pe/blob/master/core/app/models/s$p$pe/variant.rb

OptionValue:的https://github.com/s$p$pe/s$p$pe/blob/master/core/app/models/s$p$pe/option_value.rb OptionType:的https://github.com/s$p$pe/s$p$pe/blob/master/core/app/models/s$p$pe/option_type.rb

OptionValue: https://github.com/spree/spree/blob/master/core/app/models/spree/option_value.rb OptionType: https://github.com/spree/spree/blob/master/core/app/models/spree/option_type.rb

推荐答案

更​​新2:你说的没错,这不是你要找的

Updated 2: you're right, this is not what you looking for.

所以,你可以:

1)建立SQL子查询:(如果连接表中有尺寸的,具有的颜色的在同一时间,然后返回TRUE)。如何快速的将是工作 - 是一个问题...

1) Build SQL subquery: (if joined table has size and has color at the same time then return TRUE). How quick it will be working - is a question...

2)想象一下,你已经创建了一个模型Values​​Variants对表S pree_option_values​​_variants和踢出的habtm(更换2 has_​​manys + 2 has_​​manys通过)。现在,你可以搜索Values​​Variants用(option_type_id = size_id || COLOR_ID和variant_id在产品的变型IDS(阵列)),提取匹配的变种。它可以足够快...

2) Imagine you've created a model "ValuesVariants" for table "spree_option_values_variants" and kicked out habtm (replace with 2 has_manys + 2 has_manys through). Now you can search ValuesVariants with (option_type_id = size_id||color_id AND variant_id IN (array of product's variant ids)), extracting matched variants. It can be quick enough...

3)您可以使用:包括。加载到内存,第二次搜索,相关对象通过做阵列的方法。在这种情况下,关注的是在内存的使用。

3) You can use :includes. so associated objects loaded into the memory and the second search do by array methods. In this case the concern is in memory usage.

这篇关于基于两个相关联的记录的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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