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

Method 2:

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

Ordering a Collection

Method 1 (EAV Collections Only):

$collection = Mage::getModel(“…”)->getCollection()

Method 2 (Using getSelect()):

$collection = Mage::getModel(“…”)->getCollection();

Adding isActiveFilter and Friendly URLS to Product/Catalog Collection

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

Filter Collection By Attribute and Conditionals

$collection = Mage::getModel(“…”)->getCollection()
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();
$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 *