Magento ORM中的聚合函数

4
如何在Magento ORM中使用聚合函数,如sum()、count()。
假设有一个名为“test”的表,其中包含以下值:
------------------------------------- productid | qty ------------------------------------- 1 | 2 ------------------------------------- 2 | 3 ------------------------------------- 3 | 5 -------------------------------------
如果我将此表映射到我的模块中,那么我可以像下面这样获取集合数据: $_collection = Mage::getModel('mymodule/customcart')->getCollection();
如何使用COLLECTION获得与以下查询等效的结果?
select sum(qty) from test;
1个回答

16

如果你的 mymodule/customcart 集合基于 EAV,你可以使用 addExpressionAttributeToSelect 方法。

$_collection = Mage::getModel('mymodule/customcart')->getCollection();
$_collection->addExpressionAttributeToSelect('qty', 'SUM({{item_qty}})', 'item_qty')
    ->groupByAttribute('productid');

否则,您将不得不直接使用SQL进行工作:
$_collection = Mage::getModel('mymodule/customcart')->getCollection();
$_collection->getSelect()
    ->columns('SUM(item_qty) AS qty')
    ->group('productid');

在使用聚合集合与网格或分页器时要小心。它们依赖于getSelectCountSql,而该函数无法很好地处理分组查询,您可能需要提供自己的getSelectCountSql函数以返回准确的计数。


@clockworkgeek,我该如何在Magento集合中尝试此查询: select sum(qty + productid - any_other_columns) from test; - VijayS91
@VijayS 如果您无法从上面的内容中解决问题,因为您的情况不同,请发起一个新的问题,可能会引用此问题并解释其差异。 - clockworkgeek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接