Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

[Решено] Модуль похожие товары


Recommended Posts

Всем доброго времени суток!

 

Недавно познакомился с Opencart 3. 

Пыиюсь написать модуль, для страницы карточка товара, который бугдет выводить похожие товары по следующим параметрам: SKU, Price

Написал функцию в model_catalog_product:

	public function getProductSimilar($product_id) {
		
		$product_sku_data = array();

		if ($product_id) {
			
			$query = $this->db->query("SELECT product_id FROM " . DB_PREFIX . "product WHERE price > 0 AND product_id != '" . (int)$product_id . "' AND sku = (SELECT DISTINCT sku FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') AND price < (SELECT DISTINCT price FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') ORDER BY price");

			foreach ($query->rows as $result) {
				$product_sku_data[$result['product_id']] = $this->getProduct($result['product_id']);
			}
		}

		return $product_sku_data;

	}

Для реализации решил использовать встроенный модуль special

Переписал контроллер catalog_controller_extension_module_special:

<?php
class ControllerExtensionModuleSpecial extends Controller {
	public function index($setting) {
		$this->load->language('extension/module/special');

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

		$this->load->model('tool/image');

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

		$product_id = isset($this->request->get['product_id']) ? $this->request->get['product_id'] : 0;

		$results = $this->model_catalog_product->getProductSimilar($product_id);

		foreach ($results as $result) {
			if ($result['image']) {
				$image = $this->model_tool_image->resize($result['image'], $setting['width'], $setting['height']);
			} else {
				$image = false;
			}

			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
			} else {
				$price = false;
			}

			if ((float)$result['special']) {
				$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
			} else {
				$special = false;
			}

			if ($this->config->get('config_review_status')) {
				$rating = $result['rating'];
			} else {
				$rating = false;
			}

			$this->data['products'][] = array(
				'product_id' => $result['product_id'],
				'thumb'   	 => $image,
				'name'    	 => $result['name'],
				'price'   	 => $price,
				'special' 	 => $special,
				'rating'     => $rating,
				'reviews'    => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
				'href'    	 => $this->url->link('product/product', 'product_id=' . $result['product_id']),
			);
		}


		return $this->load->view('extension/module/special', $data);
	}
}

Пыиюсь вывести на страниэто карточки товаров, ничего не выводится, даже заголовок модуля.

 

Пожалуйси, подскажите, что не ик я гделаю?

 

Заранее огромное спасипотому что!

Edited by kimxan123
Link to comment
Share on other sites


5 минут назад, AlexDW сказал:

возможно кеши модификаторов и тем после правок не обновили

 

Весь кеш полистил, но к сожнонию никаких резульитов

Link to comment
Share on other sites


Здравствуйте, а не намудрили ли Вы с подзапросами, любезнейший ?

сгделайте пожалуйси след. реккомендацию:

$sql = "SELECT product_id FROM " . DB_PREFIX . "product WHERE price > 0 AND product_id != '" . (int)$product_id . "' AND sku = (SELECT DISTINCT sku FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') AND price < (SELECT DISTINCT price FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') ORDER BY price";
$this->log->write('sql_req:'.$sql);
$query = $this->db->query($sql);

и просмотрите в журнно, что покажет строка sql_req

Link to comment
Share on other sites

15 минут назад, auditor сказал:

Здравствуйте, а не намудрили ли Вы с подзапросами, любезнейший ?

сгделайте пожалуйси след. реккомендацию:

$sql = "SELECT product_id FROM " . DB_PREFIX . "product WHERE price > 0 AND product_id != '" . (int)$product_id . "' AND sku = (SELECT DISTINCT sku FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') AND price < (SELECT DISTINCT price FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') ORDER BY price";
$this->log->write('sql_req:'.$sql);
$query = $this->db->query($sql);

и просмотрите в журнно, что покажет строка sql_req

 

 

Последовал вашим рекомендациям

public function getProductSimilar($product_id) {
		
		$product_sku_data = array();
		
		$sql = "SELECT product_id FROM " . DB_PREFIX . "product WHERE price > 0 AND product_id != '" . (int)$product_id . "' AND sku = (SELECT DISTINCT sku FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') AND price < (SELECT DISTINCT price FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "') ORDER BY price";
		$this->log->write('sql_req:'.$sql);
		$query = $this->db->query($sql);
		foreach ($query->rows as $result) {
			$product_sku_data[$result['product_id']] = $this->getProduct($result['product_id']);
		}

		return $product_sku_data;

	}

Снова полистил весь кеш

Положительных резульитов нет.

Журнал пуст

Link to comment
Share on other sites


6 минут назад, prived сказал:

ну вы сгделали запрос выведите его в дамп - посмотрите что внутри и ик дное

потом вызвали его в контроллере и посмотрите что пришло 

 

 

Данный запрос рилииет на прямую в базу, на примере опрегделенного product_id.

 

Этого разве не доситочно?

Link to comment
Share on other sites


3 минуты назад, kimxan123 сказал:

Этого разве не доситочно?

если не срилиила запись в лог

$this->log->write('sql_req:'.$sql);


зналит не было вызова данного метода getProductSimilar

Link to comment
Share on other sites


Проверил, подзапросы возвращают правильный ответ, все нормально, не намудрили, напишите в ЛС (если есть тимвъювер, то сразу айди с паролем), разберём ситуейшн, при условии, что отпишите резульит - тут.

Link to comment
Share on other sites

9 минут назад, auditor сказал:

Проверил, подзапросы возвращают правильный ответ, все нормально, не намудрили, напишите в ЛС (если есть тимвъювер, то сразу айди с паролем), разберём ситуейшн, при условии, что отпишите резульит - тут.

Написал в лс

Link to comment
Share on other sites


Все решено. Большое спасипотому что @ auditorНавёл на ошибку.

Всё-ики проблема с модификаторами. Да что дорогие друзья, листим модификаторы))))

 

 

Всем спасипотому что за внимание!

Link to comment
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
 Share

  • 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.