Jacknson
Jacknson

Reputation: 5

Get Random SKU Product Number

I have the following code:

$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(); 

It works by specfing the SKU id, I want to be able to get random SKU product number and use it so

$sku = random product number from database

Upvotes: 0

Views: 1252

Answers (3)

dashbh
dashbh

Reputation: 682

I used the following script to generate a random sku from the collection. You can use it to suit your requirement also.

//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();

In your case your code should look like.......

$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(); 

Upvotes: 3

Divya Bhaloidiya
Divya Bhaloidiya

Reputation: 5064

Below code I used in project and its working fine for me :

<?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();

    }
?>

Upvotes: 0

kuba_ceg
kuba_ceg

Reputation: 930

Something like that should work fine ;)

$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();

Upvotes: 0

Related Questions