2015-02-24 57 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。