製品コレクションから5つのランダム製品IDを取得します
-
12-12-2019 - |
質問
特定の製品属性をフィルタとして使用してカスタム製品コレクションを作成しようとしています。私が成長する製品コレクションは、5つの製品をもってうまくいっていますが、コレクションからランダムに5つの製品を選択してからページ上に表示する方法を見つける必要があります。誰もがこれに似たものを開発したか、これを実装する最善の方法を知っていますか?
解決
ORDER BY RAND()
がMagentoコレクションで非常に精巧でないことをわかりました。すべてのデータは、乱数を割り当て、次にインデックスなしでソートされています。データを単なるIDにコピーするように縮小すると、それはたくさんの速い(遅いソートが残るが、あなたのような小さなカタログのための大丈夫だからまだ完璧ではありません)。
これには、getAllIds()
の修正版を作成しました:
$numberOfItems = 5;
// Step 1: Preselect ids using ORDER BY RAND()
// Filters are applied here
$productCollection = Mage::getModel('catalog/product')
->getCollection();
$productCollection
->addStoreFilter()
->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$productCollection->getSelect()->order('RAND()');
$idsSelect = clone $productCollection->getSelect();
$idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
$idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
$idsSelect->reset(Zend_Db_Select::COLUMNS);
$idsSelect->columns('e.' . $productCollection->getEntity()->getIdFieldName());
$idsSelect->limit($numberOfItems, null);
$idsSelect->resetJoinLeft();
$accessor = new ReflectionObject($productCollection);
$_bindParams = $accessor->getProperty('_bindParams');
$_bindParams->setAccessible(true);
$chosenIds = $productCollection->getConnection()
->fetchCol($idsSelect, $_bindParams->getValue($productCollection));
.
それから私はこれらのランダムIDによって製品をロードすることができます:
// Step 2: Load products
// Attributes and index data are joined here
$productCollection->addIdFilter($chosenIds);
$productCollection
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addUrlRewrite();
$productCollection->load();
.
より簡単な代替案
小さなカタログ(<10000製品)でもうまく機能する代替案は、 IDをロードして、PHPでランダムIDを選択することです:
$numberOfItems = 5;
$productCollection = Mage::getModel('catalog/product')->getCollection();
$productCollection
->addStoreFilter()
->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$candidateIds = $productCollection->getAllIds();
$numberOfProducts = count($candidateIds);
$chosenIds = [];
while ($numberOfItems) {
$randomKey = mt_rand(0, $numberOfProducts - 1);
if (!isset($chosenIds[$randomKey])) {
chosenIds[$randomKey] = $candidateIds[$randomKey];
--$numberOfItems;
}
}
$productCollection->addIdFilter($chosenIds);
$productCollection
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addUrlRewrite();
$productCollection->load();
.
詳細な分析でもっと読み、私のブログのベンチマークを見ることができます。 http://www.schmengler-se.de/en/en/en/en/ja.09/09/show-random-products-in-magento-youare -IOT-IT - 間違った/
他のヒント
を試してください
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$collection->getSelect()->limit(5);
. 所属していません magento.stackexchange