我希望在产品网格中添加一列(在管理区域中要清楚)以显示该产品已售出多少次。以下是我从其他几篇文章拼凑而成的内容:
在 app/code/local/Namespace/Qtysold/Block/Adminhtml/Catalog/Product/Grid.php
<?php
class Namespace_Qtysold_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
/* Overwritten to be able to add custom columns to the product grid. Normally
* one would overwrite the function _prepareCollection, but it won't work because
* you have to call parent::_prepareCollection() first to get the collection.
*
* But since parent::_prepareCollection() also finishes the collection, the
* joins and attributes to select added in the overwritten _prepareCollection()
* are 'forgotten'.
*
* By overwriting setCollection (which is called in parent::_prepareCollection()),
* we are able to add the join and/or attribute select in a proper way.
*
*/
public function setCollection($collection)
{
/* @var $collection Mage_Catalog_Model_Resource_Product_Collection */
$store = $this->_getStore();
if ($store->getId() && !isset($this->_joinAttributes['qty_sold'])) {
$collection->joinAttribute(
'qty_sold',
'reports/product_collection',
'entity_id',
null,
'left',
$store->getId()
);
}
else {
$collection->addAttributeToSelect('qty_sold');
}
echo "<pre>";
var_dump((string) $collection->getSelect());
echo "</pre>";
parent::setCollection($collection);
}
protected function _prepareColumns()
{
$store = $this->_getStore();
$this->addColumnAfter('qty_sold',
array(
'header'=> Mage::helper('catalog')->__('Qty Sold'),
'type' => 'number',
'index' => 'qty_sold',
),
'price'
);
return parent::_prepareColumns();
}
}
这里有几件事。1) $store->getId() 返回 0,因此它永远不会进入 setCollection 中的第一个块,这是正确的行为,因为它是管理区域吗?2)如果我强制 joinAttribute 运行,它会导致异常(无效实体...),这是意料之中的,因为报告似乎并不是一个实体,但我不太清楚整个实体业务. 3)在其他示例中(例如:http ://www.creativemediagroup.net/creative-media-web-services/magento-blog/30-show-quantity-sold-on-product-page-magento )他们使用像这样的东西:
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addOrderedQty($from, $to, true)
->addAttributeToFilter('sku', $sku)
->setOrder('ordered_qty', 'desc')
->getFirstItem();
而且我不确定是否有任何方法可以“加入”此报告/product_collection,或者是否有任何方法可以重新创建其“addOrderedQty”数据?
这是在 Magento 1.7 上。我可以根据需要提供更多详细信息。我是 Magento 开发的初学者,因此将不胜感激任何帮助(包括学习资源)。谢谢!