检测集合中是否包含数据 [英] Detect if collection contains data

查看:64
本文介绍了检测集合中是否包含数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我找不到答案.我怎么知道我的馆藏中没有数据?

It may be a simple question, but I can't find the answer. How can I know if my Collection has no data ?

如果执行$datas->getData()会返回空数组,我会执行$datas = Mage::getModel('zzz/zzz')->getCollection(),但是如何知道不执行foreach或getData的情况下我的集合是否没有数据?

I do $datas = Mage::getModel('zzz/zzz')->getCollection() if I do a $datas->getData() it returns an empty array, but how do I know if my collection has no data without doing foreach or getData ?

推荐答案

您应避免使用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());

这篇关于检测集合中是否包含数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆