2016-11-02 70 views
0

我有一个名为Document的模型,以及has_manyDocumentProperty的关系。搜索具有多个属性的模型(属性位于键=>值表中)

DocumentProperty具有id,document_id,keyvalue列。

我试图想出一个查询,让我用两个或更多键=>值对搜索文档,例如大小为A4的文档 pages = 2,但我可以'如果没有自己编写所有的SQL(当前使用ActiveRecord :: Relation),就可以找到一种方法。

实施例表中的数据:

| document_id | key | value | 
+-------------+--------+---------+ 
| 1   | size | A4  | 
| 1   | pages | 2  | 
| 2   | size | A4  | 
| 2   | pages | 3  | 
| 3   | size | A4  | 
| 3   | pages | 2  | 
| 3   | author | Brandon | 

用我的搜索,文件1和3应返回。

Rails支持吗?

+0

你解决了吗? –

回答

0

没错,ActiveRecord的支持这样的查询:

Document.joins(:document_properties) 
     .where("document_properties.key = 'size' AND document_properties.value = 'A4' OR document_properties.key = 'pages' AND document_properties.value = 2") 
     .group('documents.id') 
+0

请仔细看看我的帖子,document_properties只有4列。在我的例子中,一行有大小和A4值的关键。大小不是一列。 –

+0

@BrandonWamboldt我编辑了答案 –

0

我在轨构建模型。试试这个,先计算document_ids,

2.2.3 :002 > document_ids = DocumentProperty.where(key: 'size', value: 'A4').pluck('document_id') & DocumentProperty.where(key: 'pages', value: '2').pluck('document_id') 
    (0.3ms) SELECT `document_properties`.`document_id` FROM `document_properties` WHERE `document_properties`.`key` = 'size' AND `document_properties`.`value` = 'A4' 
    (0.3ms) SELECT `document_properties`.`document_id` FROM `document_properties` WHERE `document_properties`.`key` = 'pages' AND `document_properties`.`value` = '2' 
=> [1, 3] 
2.2.3 :003 > Document.where(id: document_ids) 
    Document Load (1.1ms) SELECT `documents`.* FROM `documents` WHERE `documents`.`id` IN (1, 3) 
=> #<ActiveRecord::Relation [#<Document id: 1, name: "first", created_at: "2016-11-02 14:07:38", updated_at: "2016-11-02 14:07:38">, #<Document id: 3, name: "three", created_at: "2016-11-02 14:07:38", updated_at: "2016-11-02 14:07:38">]> 
2.2.3 :004 >