Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
  • Sign Up

Отображение количества товаров в категории в главном меню


Recommended Posts

Здравствуйте, возникла такая проблема. Движок: ocStore 2.3.0.2.3.
В главном меню необходимо выводить количество товаров в категории.
Пр.:
Ноутбуки (452)
Смартфоны (122).
При редактировании header.php (/catalog/controller/common) смог добиться только отображения кол-ва всех товаров.
Код header.php:
 

		// Menu
		$this->load->model('catalog/category');

		$this->load->model('catalog/product');

		$data['categories'] = array();

		$categories = $this->model_catalog_category->getCategories(0);

		foreach ($categories as $category) {
			if ($category['top']) {
				// Level 2
				$children_data = array();

				$children = $this->model_catalog_category->getCategories($category['category_id']);

				foreach ($children as $child) {
					$filter_data = array(
						'filter_category_id'  => $child['category_id'],
						'filter_sub_category' => true
					);

					$children_data[] = array(
						'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
						'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
					);
				}
				
				// Level 1
				$data['categories'][] = array(
					'name'     => $category['name'],
					'children' => $children_data,
					'column'   => $category['column'] ? $category['column'] : 1,
					'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
				);
			}
		}

		$data['language'] = $this->load->controller('common/language');
		$data['currency'] = $this->load->controller('common/currency');
		$data['search'] = $this->load->controller('common/search');
		$data['cart'] = $this->load->controller('common/cart');

При замене строки "'name'  =>  $category['name'], " на "'name' => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($data) . ')' : '')," отображается количество товаров во всём магазине. При использовании getTotalProducts($filter_data) появляется ошибка.

Link to post
Share on other sites

не особо это нужная штука. Получается на каждой странице вашего сайта будет выполнятся пересчет кол-ва товаров в каждй категории-подкатегории. 

Если уж это сильно нужно то кешируйте подсчет. Для этого не обязательно покупать модуль кеширования, все делается проще. 

Link to post
Share on other sites
45 минут назад, AWARO сказал:

тормоза вам при этом обеспечены

К тормозам готов. Проблема с реализацией

Link to post
Share on other sites

Эта байда делается в модели. Эта функция

    public function getCategories($parent_id = 0) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . DB_PREFIX . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND c2s.store_id = '" . (int)$this->config->get('config_store_id') . "'  AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)");

        return $query->rows;
    }

Тут должен работать запрос, типа "SELECT *, (SELECT count(*)  FROM " . DB_PREFIX . "products" WHERE cat_id=c.id )  as cnt FROM "...

Например (не опенкарт) у меня имеется такая конструкция

       $query="SELECT (SELECT count(*) FROM `#__ose_av_core` WHERE crc='') as no_crc,(SELECT count(*) FROM `#__ose_av_core` WHERE notify='new') as new_file_count,(SELECT count(*) FROM `#__ose_av_core` WHERE notify='danger') as danger_file_count,(SELECT count(*) FROM `#__ose_av_core` WHERE scan=0) as no_scan";

 

Link to post
Share on other sites

 

Вывел.

Получается, что дополнил 

'name'  => $category['name'],

на

'name'     => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),

Потом перед

$data['categories'][] = array(

добавил

			$filter_data = array(
				'filter_category_id'  => $category['category_id'],
				'filter_sub_category' => true
			);

Вот готовый код, если кому-то понадобится:
P.S. Скорость загрузки сайта такая же.

// Menu
		$this->load->model('catalog/category');

		$this->load->model('catalog/product');

		$data['categories'] = array();

		$categories = $this->model_catalog_category->getCategories(0);

		foreach ($categories as $category) {
			$children_data = array();
			if ($category['top']) {
				// Level 2
				
				$children = $this->model_catalog_category->getCategories($category['category_id']);

				foreach ($children as $child) {
					$filter_data = array(
						'filter_category_id'  => $child['category_id'],
						'filter_sub_category' => true
					);

					$children_data[] = array(
						'name'  => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
						'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
					);
				}
				$filter_data = array(
					'filter_category_id'  => $category['category_id'],
					'filter_sub_category' => true
				);
				// Level 1
				$data['categories'][] = array(
					'name'     => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
					'children' => $children_data,
					'column'   => $category['column'] ? $category['column'] : 1,
					'href'     => $this->url->link('product/category', 'path=' . $category['category_id'])
				);
			}
		}

		$data['language'] = $this->load->controller('common/language');
		$data['currency'] = $this->load->controller('common/currency');
		$data['search'] = $this->load->controller('common/search');
		$data['cart'] = $this->load->controller('common/cart');

 

Edited by persol27
Дополнил
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.