2015-02-24 52 views
0

我有一个集合:Magento的收藏的GroupBy的getSize

$this->_totalVersions = Mage::getModel('downloads/files') 
           ->getCollection() 
           ->addFieldToFilter('customer_groups', array('like' => '%'.$customergroupId.'%')) 
           ->addFieldToFilter('main_table.is_active', 1) 
           ->getSize() 

完美的作品!但是当我添加一个group它不起作用。

$this->_totalVersions = Mage::getModel('downloads/files') 
           ->getCollection() 
           ->addFieldToFilter('customer_groups', array('like' => '%'.$customergroupId.'%')) 
           ->addFieldToFilter('main_table.is_active', 1) 
           ->getSelect()->group(array('main_table.name')) 
           ->getSize() 

我不想使用->count()count($collection) 因为它拥有90.000+项目。

有没有一种合适的方法来计算集合?

由于提前,

的Martijn

回答

4

首先,感谢Guerra的回复。你指出我正确的方向。

我只是解决了它几个小时后..诀窍是一个过滤器添加到资源集合XXXXX_Downloads_Model_Mysql4_Files_Collection

public function addGroupByNameFilter() 
{ 
    $this->getSelect()->group('main_table.name'); 
    return $this; 
} 

应用这种滤波器:

$this->_totalItems = Mage::getModel('downloads/files') 
     ->getCollection() 
     ->addFieldToFilter('customer_groups', array('like' => '%'.$customergroupId.'%')) 
     ->addFieldToFilter('main_table.is_active', 1) 
     ->addGroupByNameFilter() 
     ->getSize() 

的作品就像一个魅力!这样我会保留我的XXXXXXX_Downloads_Model_Mysql4_Files_Collection对象。 :)

干杯,

的Martijn

+0

太棒了!添加params'groupBy($ field,$ table = null)'使它变得完美 – cottton 2015-10-23 10:55:01

2

的方法 “的getSize()” 是在Varien_Data_Collection实现的,当你调用 “getSelect()” 您的收藏它返回一个 “Zend_Db_Select对象” 的对象,这一次没有实现getSize方法。

因此,您可以使用magento在集合上实现getSize但在您的Zend_Db_Select中实现的方式,您不能仅在Zend_Db_select中对集合进行分组。

的Magento这样做:

$countSelect = clone $this->getSelect(); 
$countSelect->reset(Zend_Db_Select::ORDER); 
$countSelect->reset(Zend_Db_Select::LIMIT_COUNT); 
$countSelect->reset(Zend_Db_Select::LIMIT_OFFSET); 
$countSelect->reset(Zend_Db_Select::COLUMNS); 

// Count doesn't work with group by columns keep the group by 
if(count($this->getSelect()->getPart(Zend_Db_Select::GROUP)) > 0) { 
    $countSelect->reset(Zend_Db_Select::GROUP); 
    $countSelect->distinct(true); 
    $group = $this->getSelect()->getPart(Zend_Db_Select::GROUP); 
    $countSelect->columns("COUNT(DISTINCT ".implode(", ", $group).")"); 
} else { 
    $countSelect->columns('COUNT(*)'); 

明白了吗? Magento重置查询的所有“重”参数,只需使用“COUNT()”进行查询,但如果您需要使用组,则COUNT()会计数您的组,因此您可以模拟该组的组合结果与DISTINCT。