2010-11-10 32 views
4
function getIdModelsSliderJuwels(){ 
$collection = Mage::getModel("catalog/product")->getCollection(); 
$collection->addAttributeToFilter("attribute_set_id", 27); 
    $collection->addAttributeToSelect('modellijnen'); 
    // $collection->setRandomOrder(); 
    // $collection->getSelect()->limit( 5 ); 
return $collection; 
} 

您好,查詢Magento的限制+ ORDER BY RAND()

我想知道如何設置在Magento運行,因爲 $collection->getSelect()->limit(5);不起作用限制到您的查詢。

另外如何隨機選擇,$collection->setRandomOrder();也不起作用。

txs。

+0

「不工作」是什麼意思?你會得到什麼錯誤? – 2010-11-10 11:55:29

+0

嘗試查看結果SQL查詢:echo $ collection-> getSelect(); – 2010-11-10 12:24:52

+0

有限制我得到沒有錯誤,但我回來了所有modellijnen而不是5 – 2010-11-10 12:24:56

回答

3

嘗試使用

$收藏 - > setPageSize(5) - > setCurPage(1);

8

setRandomOrder不適用於產品集合,僅適用於相關產品。你必須把它與自己添加該代碼:

$collection->getSelect()->order(new Zend_Db_Expr('RAND()')); 

在同一時間設置兩個頁面大小和數量的快捷方式是:

$collection->setPage($pageNum, $pageSize); 
3

正如clockworkgeek說,使用$collection->getSelect()->order(...)方法隨機化訂單。要限制它只是$n數量的項目,您還可以使用

$collection->getSelect()->limit($n); 
+0

它真的有用嗎? – 2013-03-07 08:40:13

+1

我現在在一家直播店工作。 – 2013-03-08 15:04:42

0

使用ORDER BY RAND()以隨機順序需要進行全表掃描和排序返回的項目列表。它會對錶中大量行的性能產生負面影響。

如何優化此查詢有幾種可能的解決方案。 Magento爲此提供了一個本地解決方案。

orderRand()方法Varien_Db_Select和數據庫適配器允許爲ORDER BY指定隨機順序和槓桿指數。指定ORDER BY子句中使用某個整數索引列的名稱,例如:

$collection->getSelect()->orderRand('main_table.entity_id'); 

實施詳見Varien_Db_Adapter_Pdo_Mysql::orderRand()