0

我有以下代码:

$sku = $id; 
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds(); 

它通过指定 SKU id 来工作,我希望能够获得随机的 SKU 产品编号并使用它

$sku = random product number from database
4

3 回答 3

3

我使用以下脚本从集合中生成随机 sku。您也可以使用它来满足您的要求。

//Geting a random sku from collection

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$randomSku = $collection->setPage(1, 1)->getFirstItem()->getSKU();

在您的情况下,您的代码应该看起来像......

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_product = $collection->setPage(1, 1)->getFirstItem()->load();

$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds(); 
于 2013-10-09T13:28:11.763 回答
0

像这样的东西应该可以正常工作;)

$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$collection->setPage(1, 1);
$_product = $collection->getFirstItem();
于 2013-10-09T10:25:22.913 回答
0

下面是我在项目中使用的代码,它对我来说工作正常:

<?php 

    // get Random prdocut list
    $collection = Mage::getResourceModel(‘catalog/product_collection’);
    Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
    $collection->getSelect()->order(‘rand()’);
    $collection->addStoreFilter();
    $numProducts = $this->getNumProducts() ? $this->getNumProducts() : 2;
    $collection->setPage(1, $numProducts);

    foreach($collection as $product){

    echo $product->getName();

    }
?>
于 2013-10-09T10:30:52.727 回答