blank page when trying to access Magento collection - magento

I have a custom block for my customer/dashboard page, and while everything works, I cannot use the following:
public function getOrders(){
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
->setOrder('created_at', 'desc')
;
return $collection;
}
I get a blank page if I access this method. I want to load orders and display them on my dashboard. I took this query from the sales order Mage module.
Am I able to access resources from different modules?
Edit:
I limited it to return one order, but no dice.
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getCustomer()->getId())
->setOrder('created_at', 'desc')
->setPageSize(1)
->setCurPage(1);

Above code is working there is no problem in code,
Now you need to check is you are getting customer id from
Mage::getSingleton('customer/session')->getCustomer()->getId();
If you are getting customer id then error is in other code of you file or another file. It may have syntax error.

Related

Failing to fetch product collection for a given category

I've written a method that I'm calling from my list.phtml file.
The logic should simply output the number of products in the currently viewed category and the highest and lowest prices. Pretty straight forward really.
For reasons beyond my understanding it's always returning that the current category contains no products, and I can't figure out why but I presume it's because I'm not fetching the product collection correctly.
Here's the code for my method.
public function writeCatInfo(){
if(Mage::registry('current_category')){
$_productCollection=$this->getLoadedProductCollection;
$catname = Mage::registry('current_category')->getName();
$priceArray = array();
foreach ($_productCollection as $_product){
$priceArray[] = $_product->getSpecialPrice();
}
$numItems = count($_productCollection);
$highPrice = number_format(max($priceArray),2);
$lowPrice = number_format(min($priceArray),2);
$infostring = ucwords($catname)." contains ".$numItems." products with prices ranging from £".$lowPrice." to £".$highPrice;
echo $infostring;
}
}
this will help you to get current category product collection.
$category_id = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
$category = Mage::getModel('catalog/category')->load($category_id);
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addCategoryFilter($category)
->setOrder('price', 'ASC')
->load();
Turns out my helper was extending the wrong class - Mage_Core_Helper_Abtract instead of Mage_Catalog_Block_Product_List. Changing this fixed the problem.
Please see the below code to get product collection by Category id
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*') // add all attributes - optional
->addAttributeToFilter('status', 1) // enabled
->addAttributeToFilter('visibility', 4) //visibility in catalog,search
->setOrder('price', 'ASC'); //sets the order by price

Get product sku in Magento using product ID for big collections

I have a catalog with near 90000 products. I need to retrieve all the products sku that have no image associated. With a sql query I can get the id list of all the products without image. From that ID I need to get the product sku. So, I have an $ids array with all the products without image (near 60000).
I'm trying to get all the corresponding skus by using something easy with the magento api:
foreach ($ids as $id){
$product = Mage::getModel('catalog/product')->load($id);
echo $product->getSku()."\n";
}
But this causes a PHP Fatal error: Allowed memory size... (memory size is 1024Mb and I cannot change it).
My question is: from this $ids array, how can I get all the corresponding sku without causing a memory size error? Is there a lighter way of getting a product attribute having the product id?
Currently you are loading a lot of not needed product data and this causes a fatal error. In your case you need only product sku. I am suggestion to use Magento collections.
I guess, that the following code snippet will work for you:
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $ids));
foreach($productsCollection as $product) {
echo $product->getSku();
}
Magento automatically adds the sku to the select, but pay attention, that sometimes you may want to get some custom product attribute, e.g. attribute with code "color". Then you need to add ->addAttributeToSelect('color') and the code will look like:
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $ids))
->addAttributeToSelect('color');
foreach($productsCollection as $product) {
echo $product->getSku();
echo $product->getColor();
}
If you want to get all product attributes you can use ->addAttributeToSelect('*')
To get separate attribute without loading product
$resource = Mage::getResourceSingleton('catalog/product');
$sku = $resource->getAttributeRawValue($productId, 'sku', $storeId)

Magento: Filtering reports/product_collection by category seems not to be working

I think this should be an easy problem for anyone who is a little familiar with Magento, but I'm quite new to it and found no solution yet.
I am trying to filter a reports/product_collection which I need to use to get the products ordered by their number of orders by category, example code:
$store = Mage::app()->getStore();
$category = 42; // just an example
$products = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter("status", Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setPageSize(9)
->setCurPage(1)
->addOrderedQty()
->setOrder("ordered_qty", "desc")
->setStore($store)
->addStoreFilter($store)
->addCategoryFilter(Mage::getModel('catalog/category')->load($category));
Using the addCategoryFilter() method on a catalog/product_collection works fine, but on a reports/product_collection it doesnt seem to do anything, it still queries the produts of all categories.
And by the way, the addAttributeToFilter() method seems not to be working either.
What am I missing?
Just a rambling though, but shouldn't it be more like this?
I don't think you're staging your filter correctly. IMHO
$store = Mage::app()->getStore();
$category = 42; // just an example
$products = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter("status", Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setPageSize(9)
->setCurPage(1)
->addOrderedQty()
->setOrder("ordered_qty", "desc")
->setStore($store)
->addStoreFilter($store)
->addAttributeToFilter('category_id', array('in' => $category));
Is the category you're querying set as anchor? I'd think this would cause it to include all subcat's products too.

Magento: ResourceModels throwing exceptions

I'm trying to display the number of total number of sales for the currently viewing product on a block, so far i have, with the help of a stackoverflow thread:
$product = Mage::registry('current_product')->getId();
$productID = Mage::getModel('catalog/product')->load($product)->getId();
$productReport = Mage::getResourceModel('reports/product_sold_collection')->addOrderedQty()->addAttributeToFilter('id',$productID);
foreach ($productReport as $product) {
$product1 = $product->getOrderedQty();
var_dump($product1);
}
I am able to load all sales quantities, but when i add the addAttributeToFilter
Fatal error: Call to a member function getBackend() on a non-object in C:\wamp\www\magento\app\code\core\Mage\Eav\Model\Entity\Abstract.php on line 816
It also happens if i pass $product directly, both are strings though. i don't know how to get the object i should pass to the addAttributeToFilter method, or if it should work with a string parameter.
Without trying it myself I suspect you need to filter by entity_id (and your second line is redundant).
$product = Mage::registry('current_product');
$productReport = Mage::getResourceModel('reports/product_sold_collection')
->addAttributeToFilter('entity_id', $product->getId())
->addOrderedQty();
$qty = $productReport->getFirstItem()->getOrderedQty();
EDIT: Product and category collections also have an addIdFilter() method for that purpose, e.g
->addIdFilter($product->getId())
See Mage_Catalog_Model_Resource_Product_Collection::addIdFilter() for more details.

Magento - making a new getProductCollection() function

Currently, if I want to get a certain collection of products, for example best-selling, I use the following, direct in my template file:
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('name')
->addAttributeToFilter('visibility', $visibility)
->addOrderedQty()
->setOrder('ordered_qty', 'desc')
$_productCollection->load();
...and then pull out the products with a foreach statement.
Can anyone explain how to make a new block to do this, that can be re-used? I've found a few examples but they always call the product list from a CMS page, whereas I want to have the call to the function embedded directly in a template file, that I can call from anywhere.
So presume I have my module set up, and my Bestseller.php file in my Block folder. In it I guess I put my function for the collection, something like
protected function _getBestsellingCollection()
{
$_BestsellingCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('name')
->addAttributeToFilter('visibility', $visibility)
->addOrderedQty()
->setOrder('ordered_qty', 'desc');
$_BestsellingCollection->load();
}
public function getLoadedBestsellingCollection()
{
return $this->_getBestsellingCollection();
}
And if so, how then do I call that from my template? Something like?
$_productCollection = $this->getLoadedBestsellingCollection()
Any help, or pointers to decent tutorials, much appreciated!
UPDATE:
I'm getting closer, but I'm having trouble with extending the Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection class. If I add my code to the end of the Collection.php file, like
public function addBestSelling()
{
$this->addAttributeToSelect('*')->addOrderedQty()->setOrder('ordered_qty', 'desc');
return $this;
}
and then use
$_productCollection = Mage::getResourceModel('reports/product_collection')->addBestSelling();
in my phtml template file, it works fine. But if I separate that code into my Bestseller.php, in my Models folder of my module, like so
class Samsmodule_FeaturedProducts_Model_Bestseller extends Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
{
public function addBestSelling()
{
$this->addAttributeToSelect('*')->addOrderedQty()->setOrder('ordered_qty', 'desc');
return $this;
}
}
and then try and use it with the following, I get an error where the page doesn't finish loading (no error message)
$_productCollection = Mage::getResourceModel('featuredproducts/bestseller')
->addMostViewed();
What am I missing?
Blocks are for rendering HTML. Each Block Object has a phtml template object. When you use $this from a phtml template you're referring back to the containing block object.
It doesn't sounds like you're rendering HTML. It sounds like you want to fetch a specific list of products to use in any block/template.
If the above assumptions are correct, instead of creating a new Block you want to create a new Model Collection class that extends the class of the object returned by
Mage::getResourceModel('reports/product_collection').
Add your method to that class, and call it with something like
Mage::getResourceModel('mymodule/my_collectionclass')-> getLoadedBestsellingCollection()

Resources