繁体   English   中英

如何计算一个表中的值,然后在另一表中显示相同的值?

[英]How do I count the value from one table and then display the same value in another table?

我要算total no of Products特定的购物清单,然后显示total count of products根据其在id为购物清单Shopping List table 。我已经创造了在产品表一和shopping_list参考

我的购物清单表如下:-

id serial NOT NULL,
  shopping_list_name character varying(255),
  shopping_list_status character varying(255) DEFAULT 'OPEN'::character varying,
  total_items character varying(255) DEFAULT 0,
  created_at timestamp without time zone NOT NULL,
  updated_at timestamp without time zone NOT NULL,
  deleted integer NOT NULL DEFAULT 0,
  CONSTRAINT shopping_lists_pkey PRIMARY KEY (id)

我的产品表如下:-

 id serial NOT NULL,
  shopping_list_id integer NOT NULL,
  product_name character varying(255) DEFAULT 'null'::character varying,
  product_category character varying(255),
  quantity integer,
  status character varying(255) DEFAULT 'OPEN'::character varying,
  deleted integer NOT NULL DEFAULT 0,
  CONSTRAINT products_pkey PRIMARY KEY (id)

谁能帮帮我吗:-

所以你会有类似的东西

class ShoppingList < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :shopping_list
end

然后为了获得购物清单的产品数量

@my_shopping_list.products.count

并获取数量

@my_shopping_list.products.sum(:quantity)

您的购物清单上可以有某种类型的缓存,因此可以说,您在ShoppingList上有一个名为products_quantity的整数字段,默认情况下为0(确保默认为0,而不是nil)。

然后在您的产品模型上,您可以执行以下操作

class Product < ActiveRecord::Base
  after_create :update_shopping_list

  def update_shopping_list
    shopping_list.update_attribute(:products_quantity, shopping_list.products_quantity + self.quantity)
  end
end

在这种情况下,您不必在“ shopping_list_id =”的产品中执行查询SELECT SUM(quantity)。

我不确定我是否回答您的第二个问题,但是如果您还有其他问题,或者您想问其他问题,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM