コレクションからすべてのIDを取得する最も効率的な方法
-
16-10-2019 - |
質問
過去に製品コレクションのすべてのIDを取得するために、私は常に使用してきました getAllIds
コレクションでは、これがデータなどの完全なコレクション負荷を妨げる方法であると信じています。
しかし、私は実際に今日の方法を見て、それはコレクションをロードし、各アイテムを反復してIDアレイを取得します。
public function getAllIds()
{
$ids = array();
foreach ($this->getItems() as $item) {
$ids[] = $this->_getItemId($item);
}
return $ids;
}
私の質問は、コレクションからIDフィールドのみを取得する最も効率的な方法は何ですか?
解決
実際 getAllIds
それを行う最良の方法です。たとえば、製品コレクションリソースモデルでは、この方法は次のようになります。
public function getAllIds($limit = null, $offset = null)
{
$idsSelect = $this->_getClearSelect();
$idsSelect->columns('e.' . $this->getEntity()->getIdFieldName());
$idsSelect->limit($limit, $offset);
$idsSelect->resetJoinLeft();
return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
}
そのため、すべてが単一の選択から取得され、反復は必要ありません。また、抽象的なリソースモデルでは、次のようになります。
public function getAllIds()
{
$idsSelect = clone $this->getSelect();
$idsSelect->reset(Zend_Db_Select::ORDER);
$idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
$idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
$idsSelect->reset(Zend_Db_Select::COLUMNS);
$idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
return $this->getConnection()->fetchCol($idsSelect);
}
だから拡張するすべて Mage_Core_Model_Resource_Db_Collection_Abstract
特に指定されていない限り、これを使用する必要があります。
あなたが見た方法は基本クラスから来ています Varien_Data_Collection
しかし、それは子供たちに上書きされます。
他のヒント
この場合、コレクションオブジェクトを使用できます
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('entity_id');
[...]
do your loop
[...]
addAttributeToSelect
にとって entity_id
本当に必要ではありませんが、私がそれを入れて、必要なフィールドを追加する目的を示すために、あなたが完了です!
あなたが見つけるコレクションの詳細 このウィキページで
より最適化されています
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->reset(Zend_Db_Select::COLUMNS);
$collection->getSelect()->columns('entity_id');
$collection1Ids[] = $collection->getAllIds();
所属していません magento.stackexchange