没有UNION的库存SQL查询?

Ben*_*zco 6 sql sqlite activerecord ruby-on-rails

我正在设计一个库存系统,它有用户,产品,buy_leads,订单(授权buy_leads),输入输出.

class Product < ActiveRecord::Base
  has_many :buy_leads
end

class BuyLead < ActiveRecord::Base
  belongs_to :product
  has_one :order
end

class Order < ActiveRecord::Base
  belongs_to :buy_lead
  belongs_to :user, :foreign_key => :authorized_by
  has_many :inputs
end

class Input < ActiveRecord::Base
  belongs_to :order
  has_many :outputs
end

class Output < ActiveRecord::Base
  # Associations
  belongs_to :input
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

输入和输出具有数量值.为了获得产品的库存,以及特定产品的库存我在两个原始SQL查询使用UNION,通过使输出量负,然后组,总结他们一起:

class InventoryController < ApplicationController

  def index
    @inventory = Input.find_by_sql products_inventory_sql
  end

  def show
    @inventory = Input.find_by_sql product_inventory_sql(params[:id])
  end

private

  def inputs_sql
    "SELECT b.*, p.*, i.order_id,
            i.id AS input_id,
            i.quantity AS quantity     
     FROM inputs i
          JOIN orders r ON r.id = i.order_id
          JOIN buy_leads b ON b.id = r.buy_lead_id
          JOIN products p ON p.id = b.product_id"
  end

  def outputs_sql
    "SELECT b.*, p.*, i.order_id,
            i.id AS input_id,
            (o.quantity * -1) AS quantity
     FROM outputs o
          JOIN inputs i ON i.id = o.input_id
          JOIN orders r ON r.id = i.order_id
          JOIN buy_leads b ON b.id = r.buy_lead_id
          JOIN products p ON p.id = b.product_id"
  end

  def products_inventory_sql
    "SELECT *, SUM(quantity) AS remaining_qty
     FROM (#{inputs_sql} UNION #{outputs_sql})
     GROUP BY product_id"
  end

  def product_inventory_sql(id)
    "SELECT *, SUM(quantity) AS remaining_qty
     FROM (#{inputs_sql} UNION #{outputs_sql})
     WHERE product_id = #{id}
     GROUP BY order_id, input_id"
  end

end
Run Code Online (Sandbox Code Playgroud)

它有效,但我想使用named_scope的功能来链接ActiveRecord中的查询,并能够执行以下操作:

Product.inputs.by_product(id)
Product.inventory.by_product(id)
...
Run Code Online (Sandbox Code Playgroud)

任何想法,还是我必须更改架构以获得更方便的架构?谢谢!

Dra*_*ken 2

解决这个问题的可能性有太多,你到底想从这些报告中得到什么?

购买订单?产品?输入/输出?

(我将其发布为答案,因为我无法评论您的问题,如果您能请启发我,我将更新答案)

更新

尝试这个

#on input
named_scope :by_product, lambda {|id| {:joins => {:orders => {:buy_leads => :products}}, :conditions => ['products.id = ?', id]}}
Run Code Online (Sandbox Code Playgroud)

您可以通过调用获取与该产品 ID 匹配的输入

Input.by_product(25)
Run Code Online (Sandbox Code Playgroud)

如果这就是您所寻找的,我想您现在也可以设法按产品进行输出:]