在PostgreSQL的HSTORE中查找键值对

时间:2016-05-23 13:29:01

标签: ruby-on-rails postgresql

给定表格games和列identifiers,其类型为HSTORE

| id | name             | identifiers                        |
|----|------------------|------------------------------------|
| 1  | Metal Gear       | { sku: 109127072, ean: 512312342 } |
| 2  | Theme Hospital   | { sku: 399348341 }                 |
| 3  | Final Fantasy    | { ean: 109127072, upc: 999284928 } |
| 4  | Age of Mythology | { tbp: 'a998fa31'}                 |
| 5  | Starcraft II     | { sku: 892937742, upc: 002399488 } |

如何找到一组给定的键值对是否在数据库中至少有一个匹配?

例如,如果我提供此数组:[ {sku: 109127072 }, { upc: 999284928 } ],我应该看到:

| id | name           | identifiers                        |
|----|----------------|------------------------------------|
| 1  | Metal Gear     | { sku: 109127072, ean: 512312342 } |
| 3  | Final Fantasy  | { ean: 109127072, upc: 999284928 } |

1 个答案:

答案 0 :(得分:0)

对于rails 5,您应该尝试使用or运算符,如:

h = { sku: 109127072, upc: 999284928 }
rela = Person.where("identifiers -> ? = ?", h.keys.first, h[h.keys.first])
h.keys[1..-1].reduce(rela) {|rela, key| rela.or("identifiers -> ? = ?", key, h[key]) }
# => relation with ored-arguments

对于非第5个轨道,您应使用arel as descibed here