Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1288389
  • 博文数量: 315
  • 博客积分: 10397
  • 博客等级: 上将
  • 技术积分: 3731
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-07 21:21
文章分类

全部博文(315)

文章存档

2015年(10)

2014年(3)

2013年(2)

2012年(8)

2011年(8)

2010年(29)

2009年(59)

2008年(77)

2007年(119)

分类: 系统运维

2009-11-05 12:48:45

Using Collections in Magento
Last modified by Gregory PLANCHAT on Thu, July 23, 2009 10:20

|  

This Wiki Article is under construction.

A collection is a Model type containing other Models, it is basically used in Magento to handle product lists (ie. from a category or a bundle option), but not only.

TO DO: Explain how Magneto Implements a collection – Use this to explain how magento implements a collection by looking at code in a model, so that people can learn to write their own collections

This is a simple example of loading some product collection from a category and ordering them on their product name using Magento’s API.

  1. $collection = Mage::getModel(‘catalog/category’)->load($categoryId)
  2.     ->getProductCollection()
  3.     ->addAttributeToSort(‘name’, ‘ASC’);

To sort using multiple Fields, you can chain calls to the Collection’s method addAttributeToSort(preferred)

  1. $collection = Mage::getModel(‘module/model_name’)->getCollection()
  2.     ->addAttributeToSort(‘order’, ‘ASC’)
  3.     ->addAttributeToSort(‘last_name’, ‘ASC’)
  4.     ->addAttributeToSort(‘first_name’, ‘ASC’)
  5. ;

TODO: use Magento’s API use cases, not Zend_Db_Select ones.

You can also pass IF/THEN statements, but be sure to use the proper quotation of your table’s fields.

  1. $collection = Mage::getModel(‘module/model_name’)->getCollection();
  2. $collection->getSelect()->order( array(‘IF(`order`>0, `order`, 9999) ASC’,
  3.      ‘last_name ASC’, ‘first_name ASC’) );

In this example, the table will be sorted by the order field, then by last name, then by first name, where order is greater than zero, followed by order being equal to or less than zero, all ascending.

Joining Tables

To add SQL joins to a select

  1. $collection = Mage::getModel(‘module/model_name’)->getCollection();
  2. $collection->getSelect()->join( array(‘table_alias’=>$this->getTable(‘module/table_name’)), ‘main_table.foreign_id = table_alias.primary_key’, array(‘table_alias.*’), ’schema_name_if_different’);

In this example the join method takes an array of alias⇒table_name key pairs, then a standard join clause using `main_table` to refer to the original select, then an array of fields to be retrieved in the join (defaults to *), a different schema can be specified as a last parameter.

→join defaults to an inner join, others can be used:

→joinInner() →joinLeft() →joinRight() →joinFull() →joinCross() →joinNatural()

See lib/Zend/Db/Select.php for source.

阅读(1175) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~