Collections, Models and Queries

Models

Loading an item:

<?php Mage::getModel('catalog/category')->load($id);

Loading by attribute:

<?php Mage::getModel('catalog/category')->load(‘url_key’, $key);

Collections

Adding an item collection

<?php $collection->addItem($item);

Eav’s AddAttributeToFilter

The addAttributeToFilter for EAV is interchangeable with addFieldToFilter (which non-eav collections use)

Less Than

<?php $products->addAttributeToFilter('price', array('lt' => 100));

Greated Than

<?php $products->addAttributeToFilter('price', array('gt' => 100));

In

<?php $products->addAttributeToFilter('sku', array('in' => array('1222333', 'ABC 456')));

String Equal

<?php $products->addAttributeToFilter('sku', array('in' => array('1222333', 'ABC 456')));

List of methods from Varien_Db_Adapter_PDO

<?php
$conditionKeyMap = array(
            'eq'            => "{{fieldName}} = ?",
            'neq'           => "{{fieldName}} != ?",
            'like'          => "{{fieldName}} LIKE ?",
            'nlike'         => "{{fieldName}} NOT LIKE ?",
            'in'            => "{{fieldName}} IN(?)",
            'nin'           => "{{fieldName}} NOT IN(?)",
            'is'            => "{{fieldName}} IS ?",
            'notnull'       => "{{fieldName}} IS NOT NULL",
            'null'          => "{{fieldName}} IS NULL",
            'gt'            => "{{fieldName}} > ?",
            'lt'            => "{{fieldName}} < ?",
            'gteq'          => "{{fieldName}} >= ?",
            'lteq'          => "{{fieldName}} <= ?",
            'finset'        => "FIND_IN_SET(?, {{fieldName}})",
            'regexp'        => "{{fieldName}} REGEXP ?",
            'from'          => "{{fieldName}} >= ?",
            'to'            => "{{fieldName}} <= ?",
            'seq'           => null,
            'sneq'          => null
        );
  

Performing OR Queries

ORs with the same attributes

<?php $products->addAttributeToFilter('sku', array(array('eq' => '1222333'), array('eq' => 'LLAPGOCH-SIMPLE' ));

ORs with different attributes

<?php
$collection->addAttributeToFilter(
    array(
        array('attribute'=> 'sku','like' => 'value'),
        array('attribute'=> 'otherattribute','nin' => array(1, 2, 3)),
        array('attribute'=> 'anotherattribute','like' => 'value'),
    )
);

Ordering

<?php
$collection->setOrder('attribute', Varien_Data_Collection::SORT_ORDER_DESC);
$collection->setOrder('attribute', Varien_Data_Collection::SORT_ORDER_ASC);

Useful Methods

<?php
// Gets a list of all Ids within a collection
$collection->getAllIds();

// Gets the last page number of a collection (when using the page functions)
$collection->getLastPageNumber();

// Get the pagesize of a collection
$collection->getPageSize();

// Get the size of the collection (similar to count, but the result is cached)
$collection->getSize(0);

// Getting a specific item(s)
$collection->getFirstItem();
$collection->getLastItem();
$collection->getItems();

// Clearing a collection (allows reloading)
$collection->clear();

// Converts the collection to an XML String
$collection->toXML();

Iterating Collections

Sometimes, large collections will cause memory issues in PHP. One solution, is to use Magento’s core/resource_iterator. This is the only purpose of this class:

<?php
public function output(){
        $products = Mage::getResourceModel('catalog/product_collection')

                // When adding attributes to the collection, make sure to use the the second parameter 'inner', otherwise the resource iterator won't pull them out.
        $products->addFieldToFilter('price', array('gt' => 300))
            ->addAttributeToSelect(array('name', 'image', 'url_key', 'price', 'visibility'), 'inner');

        Mage::getSingleton('core/resource_iterator')->walk(
            $products->getSelect(),
            array(array($this, 'walkCallback'))
        );

    }

    public function walkCallback($args) {
        $product = Mage::getModel('catalog/product');
        $product->setData($args['row']);

        var_dump($args['row']);
    }

  • The second join parameter must be ‘inner’ to pull the required data out using this method.

Joining Tables in a Collection

<?php
$collection->join(
	array('banner_item' => 'llapgoch_banners/banner_item'),
	'banner_item.banner_id=main_table.banner_id',
        array('banner_item_title' => 'title')
);

– The first parameter of the join, is the table to join onto. It’s an array, the key of the array being the alias that we’ll use for the table.
– The second parameter is the ON part of the query, I.e. the query to join the two tables together. Use the alias name given in the first parameter to reference the table that we’re joining on, and Magento uses the alias main_table for the table to which this collection refers.
– The third parameter is the fields which should be selected from the table we’re joining on. Leaving this parameter as null will cause Magento to select everything from the table; **This could overwrite variables with the same name from the main table if they clash **. As in the example, this parameter can be used as key value pairs, the key becoming the field’s alias in the query.

Left Joining

  • The collection object doesn’t have a left join method itself, so the collection’s select object needs to be used:
    <?php
    $collection->getSelect()->joinLeft(
    	array('banner_item' => $collection->getTable('llapgoch_banners/banner_item')),
    	'banner_item.banner_id=main_table.banner_id',
    	array('banner_item_title' => 'title')			
    );
    

  • The select object is an instance of Varien_Db_Select, this extends Zend_Db_Select, which is where this method is defined.

  • The first parameter is the table name (which needs to be resolved by the getTable method, either on the collection or connection object), this needs to be done here and not in the collection object’s join method because the collection object performs this operation for us.
  • In the example, we use an array as the first parameter instead of just the table name. The key of this array becomes the alias for the table.
  • The second parameter is the ON query. Use the alias (if defined) from the first parameter. Main table is the table for which the collection refers to.
  • The third parameter is the columns is the columns we would like to select from the joined table. Leaving this as null (default) will cause all columns to be selected. If no columns are required (E.g. we’re just joining to use the data for an aggregate query), then pass an empty array in as this parameter.

Inner Join

  • The select object also includes an inner join method, if the collection’s join method can’t be used:
    <?php
    $collection->getSelect()->joinInner(
    	array('banner_item' => $collection->getTable('llapgoch_banners/banner_item')),
    	'banner_item.banner_id=main_table.banner_id',
    	array('banner_item_title' => 'title')			
    );
    

Grouping

<?php
$collection->getSelect()->group('main_table.banner_id');

– The collection’s select object needs to be employed to group by a column. main_table references the table to which the collection refers to.

Adding aggregate queries

Method One

<?php
$collection->addExpressionFieldToSelect('num_banner_items', 'COUNT(*)', null);

– The first parameter is the fieldset name the value will be assigned to
– The second parameter is the query, aggregate or otherwise.
– The third parameter can be null, or an array of key values used in replacing values specified in the query between double curly brackets: {{value_to_be_replaced}}

Method Two 

<?php
$collection->getSelect()->columns('COUNT(*) as num_banner_items');

– This will add the parameter ‘num_banner_items’ to the collection object’s items.

Randomly Ordering a Collection

Method One

<?php
$collection->getSelect()->orderRand();

Method Two

<?php
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));

– See the note later on as to what the Zend_Db_Expr object actually is.

Adding a Straight Where Query

<?php
$collection->getSelect()->where('main_table.banner_id <= 1');

Limiting using the Select Object

  • Instead of setting the and page size on the collection, a limit can be called directly on the select object:
    <?php
    $collection->getSelect()->where('main_table.banner_id <= 1');
    

### Getting a collection’s full query ###

<?php
$collection->getSelect()->assemble()

Having

  • Use having to filter on aliases that have been set up either in the $collection->getSelect()->columns method or the $collection->addExpressionFieldToSelect method.
    <?php
    $collection->getSelect()->having('COUNT(*) = ?', 2);
    
    • Note: When using havings or aggregate queries in an admin grid, be careful as Magento will strip off all column names when it performs its pagination queries. You won’t be able to use aggregate aliases in the having, so use the aggregate function again.

The Zend_Db_Expr Object

This is an object which accepts an expression as its parameter. All the object does is cast the value passed in to a string, and then give it back in its _toString() method:

<?php
class Zend_Db_Expr
{
    protected $_expression;
    
    public function __construct($expression)
    {
        $this->_expression = (string) $expression;
    }
    public function __toString()
    {
        return $this->_expression;
    }
}

Flat Catalog

More complex queries may fail id flat catalog is toggled. These can be adapted and checked for using the following check:

  public function isProductFlatCatalogOn()
    {
        $flatHelper = Mage::helper('catalog/product_flat');
        return $flatHelper->isAvailable() && !Mage::app()->getStore()->isAdmin() && $flatHelper->isBuilt(true);
    }