且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测集合中是否包含数据

更新时间:2023-11-29 16:09:16

您应避免使用count或您的收藏集.原因如下:

You should avoid using count or your Collections. Here's why:

Mage_Core_Model_Resource_Db_Collection_Abstract(几乎所有Magento集合继承的集合模型)都没有定义count(),因此在集合上使用count很有可能会以Varien_Data_Collection::count()结尾,这非常糟糕选项,因为它会执行load()集合,然后计算已加载的对象:

the Mage_Core_Model_Resource_Db_Collection_Abstract (Collection Model that is inherited by almost all Magento Collections) does not have count() defined, so using count on your Collection you'll most likely end up with Varien_Data_Collection::count() which is very bad option, since it does a collection load() and then counts the loaded objects:

/**
 * Retireve count of collection loaded items
 *
 * @return int
 */
public function count()
{
    $this->load();
    return count($this->_items);
}

拥有较大的馆藏(尤其是EAV馆藏)将导致加载您的所有馆藏数据-这可能需要很多时间.

Having a large collection (especially EAV collection) will make result in loading ALL of your Collection data - this can take a lot of time.

相反,您应该使用Varien_Data_Collection_Db::getSize()方法,该方法将运行SQL查询以仅获取计数,与检索所有类型的数据以进行Collection加载相比,优化程度更高:

Instead you should use Varien_Data_Collection_Db::getSize() method, which will run the SQL query to get count only, much more optimized compared to retrieving all kind of data for Collection load:

/**
 * Get collection size
 *
 * @return int
 */
public function getSize()
{
    if (is_null($this->_totalRecords)) {
        $sql = $this->getSelectCountSql();
        $this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams);
    }
    return intval($this->_totalRecords);
}

除此之外,load之后的集合不能以任何方式修改.例如,在使用count()之后,您将无法在任何时候应用更改排序顺序的其他过滤器.

In addition to that, after load collection can not be modified in any way. For example you won't be able to apply additional filters of change sort order at any point after using count().

所以正确的答案应该是:

So correct answer should be:

$collection = Mage::getModel('zzz/zzz')->getCollection();
var_dump($collection->getSize());