0

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

我已经用不同的关键字通过谷歌进行了深入的搜索,但我得到的只是过时的插件、对 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(),我在各种搜索结果中发现的一种方法不起作用。现在我真的不知道我还能尝试什么并寻求一些非常感谢的帮助。谢谢!

4

2 回答 2

0

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

当我前几天解决这个问题时,我决定使用直接的 ORM 方法而不是对象来获得更好的性能。

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

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

在我的脚本中,我选择了后一种路径。我已经对其进行了修改以满足您的逻辑要求。我还添加了几个joins来获取类别名称,您可能不需要它。但是说够了 :) 这是我的test.phpshell 脚本的代码:

<?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();

test.php要使用它,只需在你的shell文件夹中创建一个文件并将我提供的代码插入到文件中。看看usageHelp你是否不熟悉命令行 php 调用。

PS 在那里添加了一些基准测试来跟踪您的 mem_usage 和时间。

更新在进一步审查该问题后,我发现仅使用Zend_Db适配器即可获得每个类别的畅销书的更优雅的方法。结果将仅包含category_id=>product_id连接(不是 Magento 对象),但它更容易且整体更好。此代码应在基准测试块之间进入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";
    });
于 2012-10-11T11:30:02.303 回答
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; ?>

希望这可以帮助

于 2012-10-11T11:36:03.530 回答