在Magento 1.7中显示导航中每个类别的畅销书

时间:2012-10-11 09:39:58

标签: php navigation magento-1.7

我正在寻找按类别获得最畅销产品的可能性,以便在导航的特定部分显示它。显示产品不是问题,而是获得它们。

我已经使用不同的关键字通过谷歌进行了密集搜索,但我得到的都是过时的插件,对bestseller.phtml的修改(不再在Magento 1.7中退出)并在资源模型上设置过滤器但我还没有发现了我的任何结果。

所以我试着亲自拿到产品(到目前为止,它应该得到任何产品的销售,而不是最好的产品):

$category->getId();
    $children = $category->getChildren();

    foreach($children as $child)
    {
        $childCategoryIdString = $child->getId();
        $childCategoryId = substr($childCategoryIdString, 14);

        $childCategory = Mage::getModel('catalog/category')
            ->load($childCategoryId);

        $productCollection = Mage::getModel('catalog/product')
            ->getCollection()
            ->addCategoryFilter($childCategory)
            ->load();

        $allIds = $productCollection->getAllIds();

        for($i = 0; $i < count($allIds); $i++)
        {
            $product = Mage::getModel('catalog/product')->load($allIds[$i]);
            echo $product->getOrderedQty() . '_';
        }
    }

这有两个问题:首先它让Magento变慢了。第二个$product->getOrderedQty(),我在搜索的各种结果中找到的方法不起作用。现在我真的不知道我还能尝试什么,并寻求一些非常感谢的帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

您在示例脚本中使用了大量对象包装器。像load封装到多个循环中的方法会产生巨大的延迟,并可能产生大量的内存使用(基于产品集合大小)。

有一天,当我解决这个问题时,我决定使用直接的ORM方法代替对象以获得更好的性能。

有两种可能的方式来展示畅销书。使用聚合畅销书表(如sales_bestsellers_aggregated_daily)消耗的资源越少,但它有很大的缺点 - 这些表中的数据不会自动更新。它在管理员报告部分中使用,仅在您选择刷新统计信息时才会更新。

另一种更可靠的方法是加入sales_flat_order_item表来检索每个产品的sales_qty。显然它消耗的资源更多,因为你必须自己计算它。

在我的剧本中,我选择了后一条道路。我修改它以满足您的逻辑要求。此外,我添加了几个joins来获取类别名称,您可能不需要它。但足够说话:)这是我的test.php shell脚本的代码:

<?php
require_once 'abstract.php';

/**
 * Magento Test Bestsellers script
 *
 * @category    Mage
 * @package     Mage_Shell
 */
class Mage_Shell_Test extends Mage_Shell_Abstract
{
    /**
     * Run script
     *
     */
    public function run()
    {
        // benchmarking
        $memory = memory_get_usage();
        $time = microtime();
        echo "Starting mem usage: $memory\n";

        $catId = $this->getArg('category');
        /** @var $collection Mage_Catalog_Model_Resource_Product_Collection */
        $collection = Mage::getResourceModel('catalog/product_collection');
        // join sales order items column and count sold products
        $expression = new Zend_Db_Expr("SUM(oi.qty_ordered)");
        $condition = new Zend_Db_Expr("e.entity_id = oi.product_id AND oi.parent_item_id IS NULL");
        $collection->addAttributeToSelect('name')->getSelect()
            ->join(array('oi' => $collection->getTable('sales/order_item')),
            $condition,
            array('sales_count' => $expression))
            ->group('e.entity_id')
            ->order('sales_count' . ' ' . 'desc');
        // join category
        $condition = new Zend_Db_Expr("e.entity_id = ccp.product_id");
        $condition2 = new Zend_Db_Expr("c.entity_id = ccp.category_id");
        $collection->getSelect()->join(array('ccp' => $collection->getTable('catalog/category_product')),
            $condition,
            array())->join(array('c' => $collection->getTable('catalog/category')),
            $condition2,
            array('cat_id' => 'c.entity_id'));
        $condition = new Zend_Db_Expr("c.entity_id = cv.entity_id AND ea.attribute_id = cv.attribute_id");
        // cutting corners here by hardcoding 3 as Category Entiry_type_id
        $condition2 = new Zend_Db_Expr("ea.entity_type_id = 3 AND ea.attribute_code = 'name'");
        $collection->getSelect()->join(array('ea' => $collection->getTable('eav/attribute')),
            $condition2,
            array())->join(array('cv' => $collection->getTable('catalog/category') . '_varchar'),
            $condition,
            array('cat_name' => 'cv.value'));
        // if Category filter is on
        if ($catId) {
            $collection->getSelect()->where('c.entity_id = ?', $catId)->limit(1);
        }

        // unfortunately I cound not come up with the sql query that could grab only 1 bestseller for each category
        // so all sorting work lays on php
        $result = array();
        foreach ($collection as $product) {
            /** @var $product Mage_Catalog_Model_Product */
            if (isset($result[$product->getCatId()])) {
                continue;
            }
            $result[$product->getCatId()] = 'Category:' . $product->getCatName() . '; Product:' . $product->getName() . '; Sold Times:'. $product->getSalesCount();
        }

        print_r($result);

        // benchmarking
        $memory2 = memory_get_usage();
        $time2 = microtime();
        $memDiff = ($memory2 - $memory)/1000000;
        $timeDiff = $time2 - $time;
        echo 'Time spent:' . $timeDiff . "s\n";
        echo "Ending mem usage: $memory2\n";
        echo "Mem used : {$memDiff}M\n";
    }

    /**
     * Retrieve Usage Help Message
     *
     */
    public function usageHelp()
    {
        return <<<USAGE
Usage:  php -f test.php -- [options]
        php -f test.php -- --category 1

  --categories <category> Filter by Category, if not specified, all categories are outputted
  help                      This help

USAGE;
    }
}

$shell = new Mage_Shell_Test();
$shell->run();

要使用它,只需在 shell 文件夹中创建一个文件test.php,然后将我提供的代码插入到文件中。如果您不熟悉命令行php调用,请参阅usageHelp

P.S。在那里添加了一些基准测试来跟踪你的mem_usage和时间。

更新在进一步审核该问题后,我发现只使用Zend_Db适配器为每个类别获得畅销产品的更优雅方式。结果将仅包含category_id =&gt; product_id连接(不是Magento Objects),但它更容易,整体更好。此代码应在基准块之间进入run函数:

    $catId = $this->getArg('category');

    /** @var $resource Mage_Core_Model_Resource */
    $resource = Mage::getModel('core/resource');
    /** @var $adapter Zend_Db_Adapter_Abstract */
    $adapter = $resource->getConnection('core_read');

    $select = $adapter->select()
        ->from(array('c' => $resource->getTableName('catalog/category')), array('cat_id'=>'entity_id'))
        ->join(array('ccp' => $resource->getTableName('catalog/category_product')), 'c.entity_id = ccp.category_id', array())
        ->join(array('oi' => $resource->getTableName('sales/order_item')), 'ccp.product_id = oi.product_id', array('max_qty' => new Zend_Db_Expr('SUM(oi.qty_ordered - oi.qty_canceled)'), 'product_id' => 'product_id'))
        ->where('oi.parent_item_id is null')
        ->group('c.entity_id')
        ->group('oi.product_id')
        ->order('entity_id ASC')
        ->order('max_qty DESC');
    if ($catId) {
        $select->where('c.entity_id = ?', $catId);
    }
    $res = $adapter->fetchAll($select);

    $result = array();
    foreach ($res as $oneRes) {
        if (isset($result[$oneRes['cat_id']])) {
            continue;
        }
        $result[$oneRes['cat_id']] = $oneRes;
    }

    array_walk($result, function($var, $key) {
        echo 'Category Id:' . $key . ' | Product Id:' . $var['product_id'] . ' | Sales Count:' . $var['max_qty'] . "\n";
    });

答案 1 :(得分:0)

$visibility = array(
                      Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                      Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                  );
$category = new Mage_Catalog_Model_Category();
$category->load(2); //My cat id is 10
$prodCollection = $category->getProductCollection()->addAttributeToFilter('visibility', $visibility)->setOrder('ordered_qty', 'desc');
<?php foreach($_productCollection as $_product): ?>
//whatever you want
<?php endforeach; ?>

希望这会有所帮助