我正在循环浏览产品结果,如果产品是分组产品,我想获得该组中的所有产品。我这样做:
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
foreach ($products as $product) {
if ($product->getTypeId() == 'grouped'){
// how do I now get associated products of $product?
}
}
答案 0 :(得分:30)
在:
/magento/app/design/frontend/base/default/template/catalog/product/view/type/grouped.phtml
你会看到他们使用它:
<?php
$_associatedProducts = $this->getAssociatedProducts();
由于该phtml文件的类型为Mage_Catalog_Block_Product_View_Type_Grouped
,我们可以转到:
/magento/app/code/core/Mage/Catalog/Block/Product/View/Type/Grouped.php
并看到Mage_Catalog_Block_Product_View_Type_Grouped::getAssociatedProducts()
执行此操作:
<?php
$this->getProduct()->getTypeInstance()->getAssociatedProducts($this->getProduct());
因此,我们可以放心地假设$this->getProduct()
返回一个产品对象,并将其替换为您的$product
变量,如下所示:
<?php
if ($product->getTypeId() == 'grouped'){
// how do I now get associated products of $product?
$associatedProducts = $product->getTypeInstance()->getAssociatedProducts($product);
}
如果我要完全优化你的代码,我会这样写:
<?php
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('type_id', array('eq' => 'grouped'));
foreach ($products as $product) {
$associatedProducts = $product->getTypeInstance()->getAssociatedProducts($product);
// Do something with $associatedProducts
}
答案 1 :(得分:6)
或者,如果您只想获得相关产品的ID,可以使用以下方法(速度更快):
public function getAssociatedProductIds($groupedProductId)
{
$coreResource = Mage::getSingleton('core/resource');
$conn = $coreResource->getConnection('core_read');
$select = $conn->select()
->from($coreResource->getTableName('catalog/product_relation'), array('child_id'))
->where('parent_id = ?', $groupedProductId);
return $conn->fetchCol($select);
}
答案 2 :(得分:0)
按类型获取产品:
$product = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('type_id', array('eq' => 'grouped'))
->load();
$parentProductId = array();
foreach($product as $simpleProducts) {
$simpleProducts->loadParentProductIds();
array_push($parentProductId,$simpleProducts->getParentProductIds();
}