Activerecord,如何在一个连接表上连锁多个条件。

问题描述 投票:0回答:1

我想为我的产品数据库找到一种创建查询的方法。

我有这些模型

class Category < DatabaseProducts::Base
 has_many :category_searches
 has_many :products
end 

class Product < DatabaseProducts::Base
 belongs_to :category
 has_many :products_features
end 

class Feature < DatabaseProducts::Base
 has_many :products, through: :product_features
 has_many :product_features
end 

class ProductFeature < DatabaseProducts::Base
 belongs_to :feature
 belongs_to :product
end 

class CategorySearch < DatabaseProducts::Base
 belongs_to :category
end 

基本上是一个产品数据库,每个产品都有一些功能,数值都存储于 ProductFeature 连接表.这里是结构。presentional_value 是为观。raw_value 是用于搜索

create_table "product_features", force: :cascade do |t|
    t.string "raw_value"
    t.string "presentional_value"
    t.integer "product_id"
    t.integer "feature_id"
    t.boolean "searchable", default: false
    t.index ["feature_id"], name: "index_product_features_on_feature_id"
    t.index ["product_id"], name: "index_product_features_on_product_id"
  end

我在这个产品数据库中有一个Vue前端,我有多个搜索。为了创建搜索字段,我创建了category_searches表。

create_table "category_searches", force: :cascade do |t|
    t.integer "category_id"
    t.integer "feature_id"
    t.string "name"
    t.string "search_type"
    t.string "search_options", default: [], array: true
    t.index ["category_id"], name: "index_category_searches_on_category_id"
    t.index ["feature_id"], name: "index_category_searches_on_feature_id"
  end

每天晚上,当我导入数据库中的新产品时,我都会创建新的记录,或者更新这个表:对于每一个可搜索的功能,我都会存储每一个可能的搜索值。

例如,对于电视类别,在这个表中,我有以下内容

category_id: 5
feature_id: 124
search_type: boolean
values: ["Yes","No"]

category_id: 5
feature_id: 235
search_type: options
values: ["OLED","LCD","QLED"]

在我的Vue前端,对于每一个类别,我都使用这个表中的记录来绘制搜索界面,所以当我选择某个产品时,前端会用这些参数向我的搜索API发送一个请求。

category_id: 5
search_options: {"124" => "Yes", "235" => "OLED" ...}

基本上,我必须搜索每个产品 category_id=5 哪儿 search_options.

在这里,我停止:我不知道如何建立查询。

我知道我必须连接产品表和产品特征表。而且我知道如何向Activerecord查询

"查找产品,其中raw_value == ?" 或 "查找产品,其中 feature_id= ?"

这是一个简单的链式哪里。但是我不知道怎么问ActiveRecord。

"寻找产品的地方 ProductFeature 其中feature_id=124的原始值为 "Yes",feature_id=235的原始值为 "OLED",... "

ruby-on-rails activerecord
1个回答
3
投票

一个AND子句不会真正给你你想要的结果。你想要的是使用一个OR子句和GROUP以及HAVING。

f_id = ProductFeature.arel_table[:feature_id]
raw = ProductFeature.arel_table[:raw_value]
Product.joins(:product_features)
       .where(
          f_id.eq(124).and(raw.eq("Yes")).or(
            f_id.eq(12345).and(raw.eq("No"))
          )
        )
       .group("products.id")
       .having(Arel.star.count.eq(2))

这将导致下面的查询。

SELECT "products".*
FROM   "products"
       INNER JOIN "product_features"
               ON "product_features"."product_id" = "products"."id"
WHERE  ( "product_features"."feature_id" = 123
         AND "product_features"."raw_value" = 'Yes'
          OR "product_features"."feature_id" = 12345
             AND "product_features"."raw_value" = 'No' )
GROUP  BY "products"."id"
HAVING ( count(*) = 2 )
LIMIT  ?

返回所有在连接表中至少有两个匹配的产品。

你可能想使用JSONJSONB列而不是字符串列来存储值。这将帮助你减轻EAV模式的一个最大的问题,那就是把所有的东西都打成字符串列的头疼问题。

在Postgres上(可能还有MySQL),你可以使用 WHERE (columns) IN (values) 以组成一个更简单有效的查询。

class Product < ApplicationRecord
  has_many :product_features
  has_many :features, through: :product_features

  def self.search_by_features(*pairs)
    t =  ProductFeature.arel_table
    conditions = Arel::Nodes::In.new(
        Arel::Nodes::Grouping.new( [t[:feature_id], t[:raw_value]] ),
        pairs.map { |pair| Arel::Nodes::Grouping.new(
            pair.map { |value| Arel::Nodes.build_quoted(value) }
        )}
    )
    Product.joins(:product_features)
      .where(
        conditions
      ).group(:id)
      .having(Arel.star.count.eq(pairs.length))
  end
end

使用方法:

Product.search_by_features([1, "Yes"], [2, "No"], [3, "Maybe"])

SQL查询。

SELECT     "products".*
FROM       "products"
INNER JOIN "product_features"
ON         "product_features"."product_id" = "products"."id"
WHERE      
  ("product_features"."feature_id", "product_features"."raw_value")
  IN 
  ((1, 'Yes'),(2, 'No'),(3, 'Maybe'))
GROUP BY   "products"."id"
HAVING     ( COUNT(*) = 3) ) 
LIMIT $1 


0
投票

怎么样使用左联接?

Product
.left_joins(:product_features)
.left_joins(:features)
.where(product_features: {feature_id: feature_id, raw_values: "YES"})
.where(features: {feature_id: feature_id, raw_values: "OLED"})

如果有更多的表可以连接,只需添加左联接语句和where语句即可。


0
投票

我不认为ActiveRecord支持这样的查询。你可以使用普通SQL,或者 Arel翻箱倒柜等。

目前无法确认,但Arel版本可能与此类似。

products = Product.arel_table
result = params[:search_options].reduce(Product.where(category_id: 5)) do |scope, (feature_id, feature_value)|
  product_feature_table = ProductFeature.arel_table.alias("product_feature_#{feature_id}")
  join_clause = product_feature_table[:product_id].eq(products[:id]).
    merge(product_feature_table[:raw_value].eq(feature_value))
  scope.joins(product_feature_table.on(join_clause)
end
© www.soinside.com 2019 - 2024. All rights reserved.