在我的magento项目中,在我的帐户>我的订单(登录客户)下,我可以查看订单详细信息以及我订购的产品。现在,对于每个订购的产品,我想检索一个特定的属性。然而,根据我的理解,sales/order/items/renderer/default.phtml
开头的代码片段$_item = $this->getItem();
就是订单本身,所以如果我使用类似$_item->getId()
的东西,我得到的是订单id,而不是产品的。
我尝试过研究,最终得到了这个代码:
$orders = Mage::getModel('sales/order')->load($_item->getId());
foreach($orders as $order):
$is = $order->getAllItems();
foreach($is as $i):
echo $i->getProductId();
endforeach;
endforeach;
我希望我可以使用产品id来获得所说产品的其他属性,然而,我在这个代码中遇到了一个错误,无法判断错误是什么。我也尝试过这样的方法:
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('name', $name);
foreach($_productCollection as $_product):
$_temp = $_product->getResource()->getAttribute('name_en')->getFrontend()->getValue($_product);
endforeach;
但当我尝试检查产品集合中的项目数时,我总是得到0。如何在此页面中检索产品的自定义属性?
这应该会更好地工作:
$orderIncrementId = '100000010';
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
$items = $order->getAllVisibleItems();
foreach($items as $i):
echo $i->getProductId();
endforeach;
查看此处了解更多信息:http://www.magentocommerce.com/boards/viewthread/18629/
虽然Electric Jesus给出的答案有效,但它包含了在循环中加载产品的潜在性能问题。
正确的实现是首先获取订购产品的ID,然后一次加载所有产品。假设您已经加载了订单:
$orderedItems = $order->getAllVisibleItems();
$orderedProductIds = [];
foreach ($orderedItems as $item) {
$orderedProductIds[] = $item->getData('product_id');
}
$productCollection = Mage::getModel('catalog/product')->getCollection();
$productCollection->addAttributeToSelect('*');
$productCollection->addIdFilter($orderedProductIds);
$_orders = $this->getOrders();
$orderitems = $_order->getAllVisibleItems();
foreach ($_orders as $_order):
$orderitems = $_order->getAllVisibleItems();
foreach ($orderitems as $orderitem):
$product = $orderitem->getProduct();
echo $product->getId();
endforeach;
endforeach;
我有同样的问题,这是我的解决方案