SQL - 具有近查询地理编码器的关联可用记录的计数

时间:2018-03-07 06:39:57

标签: sql ruby-on-rails postgresql rails-geocoder

我有以下模特

product.rb

add_filter('body_class','add_category_to_single');
  function add_category_to_single($classes) {
     if(is_category()) {

     $term = get_queried_object();

     // Set HERE your subcategories slugs
     $sub_cats_arr = array( 'test1', 'test2', 'test2' );         


     $term_id = $term->term_id; 
     $term_slug = $term->slug; 
     $term_name = $term->name; 
     $term_taxonomy = $term->taxonomy; 
     $term_parent_id = $term->parent; 

     if ( has_term( $sub_cats_arr, $term_taxonomy ) || in_array($term_slug, $sub_cats_arr) )
        $classes[] = 'services';

    }
    // return the $classes array
    return $classes;
  }

warehouse.rb

has_many :product_warehouses, dependent: :destroy
has_many :available_warehouses, through: :product_warehouses, :source => :warehouse
reverse_geocoded_by "warehouses.latitude", "warehouses.longitude"

category.rb

has_many :product_warehouses, dependent: :destroy
has_many :products, through: :product_warehouses
geocoded_by :address
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }

我想获得特定类别的计数产品。我之前使用过以下的查询

has_many :products, dependent: :destroy

现在我想只检索特定类别的可用产品,

尝试查询以下

Category.left_outer_joins(:products).select('categories.*,count(products.id) as products_count').group("categories.id").order("categories.created_at")

但在这2个查询中,我无法获得包含0个产品的类别。如何检索特定类别的可用产品数量?

0 个答案:

没有答案