2012-02-07 56 views
7

我想在Magento的類別列表頁面上顯示查看計數。這些數據看起來像過去一樣可以通過reports/product_collection訪問,但我無法找到正確訪問它的方法。基於product_id獲取magento產品的查看計數

我基本上想提供一個產品ID並獲得返回給我的上述產品的查看計數。

+3

我碰到這個線程http://www.magentocommerce.com/boards/viewthread/27684/? – Ledgemonkey 2012-02-07 08:13:41

+0

這工作,但像線程中所述,它很慢。謝謝您的幫助! – matt 2012-02-10 03:45:45

回答

15

您可以通過Mage_Reports_Model_Resource_Product_Collection模型獲得查看次數。

// set $to and $from to an empty string to disable time range filtering 
$from = '2012-01-01'; 
$to = now(); 
$productIds = array(9, 35); // your product ids, (works as an int, too) 

$reports = Mage::getResourceModel('reports/product_collection') 
    ->addViewsCount($from, $to) 
    ->addFieldToFilter('entity_id', $productIds); 

集合中的每一項都是一個catalog/product實例與觀點屬性集,所以你可以使用$product->getViews()得到計數。

如果你不希望加載整個產品型號,只需要查看次數,你可以這樣說:

$resource = Mage::getResourceModel('reports/event'); 
$select = $resource->getReadConnection()->select() 
    ->from(array('ev' => $resource->getMainTable()), array(
     'product_id' => 'object_id', 
     'view_count' => new Zend_Db_Expr('COUNT(*)') 
    )) 
    // join for the event type id of catalog_product_view 
    ->join(
     array('et' => $resource->getTable('reports/event_type')), 
     "ev.event_type_id=et.event_type_id AND et.event_name='catalog_product_view'", 
     '' 
    ) 
    ->group('ev.object_id') 

    // add required filters 
    ->where('ev.object_id IN(?)', productIds) 
    ->where('ev.logged_at >= ?', $from) 
    ->where('ev.logged_at <= ?', $to); 

$result = $resource->getReadConnection()->fetchPairs($select); 

這給你一個數組,鍵是產品ID並且這些值是視圖計數。

+0

完美!感謝您的幫助。 – matt 2012-02-10 03:45:11

+0

什麼是使用'SELECT COUNT(*)AS查看FROM report_viewed_product_index WHERE product_id = 446'的差異? – 2017-10-22 18:28:25

+0

什麼是object_id和subject_id在report_event表中是指什麼? – 2017-10-22 18:32:48