magento get all products by category id

最简单的方法:

1
2
3
4
$categoryId = 4;		
$_category=Mage::getModel('catalog/category')->load($categoryId);
Mage::register('current_category',$_category);
$_productCollection = Mage::getSingleton('catalog/layer')->getProductCollection();

关于foreach collection的问题:

1
2
3
foreach ($_productCollection as $key=>$_product){
//这里面有自动调用load();
}

如果不想让forach自动load的话可以在前面定义

1
2
3
4
$_productCollection->load();
foreach ($_productCollection as $key=>$_product){

}

2种方法速度其实差不多,但是foreach还是稍微强点,因为毕竟优化过,至于怎么优化的,找到这段话:

One fairly unknown feature of Magento collections is that you actually don’t have to call ->load() on a collection before being able to access the items in the collection. So you can do this:

 

1
2
3
4
5
6
$orders = Mage::getResourceModel('sales/order_collection')->addAttributeToSelect('*');
# The load method is not necessary, as iterating through a collection automatically loads it, if it hasn't already been loaded.
# $orders->load();
foreach($orders as $order){
echo 'Order Id: ' . $order->getId() . "\n";
}

 
The base Varien_Data_Collection class implements the IteratorAggregate (http://php.net/manual/en/class.iteratoraggregate.php) interface which extends the Traversable (http://www.php.net/manual/en/class.traversable.php) interface. When a class extends the Traversable interface, it guarantees that that class can be iterated through using foreach(). When foreach is called on a collection, it calls the getIterator() method in the Varien_Data_Collection class and uses the value returned from that method as the value that the foreach iterates through. This is the getIterator() method:

 

1
2
3
4
5
public function getIterator()
{
$this->load();
return new ArrayIterator($this->_items);
}

 
This auto-loading functionality works for both EAV and flat-table collections.

As you can see, a collection ensures that it is loaded before running through a foreach loop. Note: collections can only be loaded once per instantiation. If you want to reload a collection, you have to call the clear() method, and then reset the select and filters before calling the load() method again.

Knowing that collections function in this way allows you to write code without explicit calls to load(). This ultimately should result in more flexible code. You can have a method in a block that loads a collection. That collection can then either be called by a template file and iterated through, or you can have another method that loads the collection from the first method, and then adds additional selects/filters to it. This practice of not explicitly calling the load() results in more flexible and reusable code.

坚持原创技术分享,您的支持将鼓励我继续创作!