BElow 是选择单个产品相关产品的函数。 我希望它以这样一种方式工作,如果没有相关产品,其他随机产品将被添加到数组中。 随机可能是同一类别的其他产品,如果同一类别中没有产品,我们可以从其他类别中获取。
protected function _prepareData()
{
$product = Mage::registry('product');
/* @var $product Mage_Catalog_Model_Product */
$this->_itemCollection = $product->getRelatedProductCollection()
->addAttributeToSelect('required_options')
->addAttributeToSort('position', Varien_Db_Select::SQL_ASC)
->addStoreFilter()
;
if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
Mage::getSingleton('checkout/session')->getQuoteId()
);
$this->_addProductAttributesAndPrices($this->_itemCollection);
}
// Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_itemCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);
$this->_itemCollection->load();
foreach ($this->_itemCollection as $product) {
$product->setDoNotUseCategoryId(true);
}
return $this;
}
谢谢阿布纳布
你可以使用 count(( 来查看是否有任何相关的产品。如果没有,则可以使用所需的任何筛选器加载新的产品集合。例如,我在下面按category_id过滤。我建议阅读Magento收藏(或这里(。
protected function _prepareData()
{
...
$this->_itemCollection->load();
// If there are no related products, find more products in same category.
if (count($this->_itemCollection) < 1) {
$this->_itemCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('required_options')
->addAttributeToFilter('category_id', $product->getCategoryId());
}
foreach ($this->_itemCollection as $product) {
...