Magento 1.9: Useful Collection Snippets

Some useful bits and bobs to do with ordering, size-limiting and getting data out of collections that I tend to often need to look up.

Limiting the Size of a Collection
Adding isActiveFilter
Loading Friendly URLs/Rewrites
Filter Collection by Attribute and Conditionals List
Get First Item From Collection

Limit Size of Collection

Method 1:

$collection = Mage::getModel(“…”)->getCollection()
->setPageSize(5)
->setCurPage(1);

Method 2:

$collection = Mage::getModel(“…)->getCollection();
$collection->getSelect()->limit(5);

Ordering a Collection

Method 1 (EAV Collections Only):

$collection = Mage::getModel(“…”)->getCollection()
->addAttributeToSort(“name”,”DESC”);

Method 2 (Using getSelect()):

$collection = Mage::getModel(“…”)->getCollection();
$collection->getSelect()->order(“name”,”ASC”);

Adding isActiveFilter and Friendly URLS to Product/Catalog Collection

$collection = Mage::getModel(“catalog/category”)->getCollection()
->addIsActiveFilter()
->addUrlRewriteToResult();

Filter Collection By Attribute and Conditionals

$collection = Mage::getModel(“…”)->getCollection()
->addAttributeToFilter(“status”,1)
->addAttributeToFilter(“post_date”,
array(“lt“=>date(“Y-m-d”,strtotime(“+1 day”)) )
);

lt means “less than”.  You can use the following conditionals.

  • lt – less than
  • gt – greater than
  • gteq – great than or equal to
  • lteq – less than or equal to
  • like
  • nlike – Not like
  • eq – equal to (default)
  • neq – not equal to
  • in
    (e.g.  $collection->addAttributeToFilter(“id”, array(“in”=>array(1,2,5,23) );
  • nin – non in
  • null
    (e.g.  $collection->addAttributeToFilter(“id”, array(“null”=>true );
  • notnull

Get First Item From Collection

$collection = Mage::getModel(“…”)->getCollection();
if($collection->count()){
$firstItem = $collection->getFirstItem();
$firstItemName = $collection->getFirstItem()->getName();
}

 

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Apply your human brain cells and complete this highly complicated maths problem *