Yurinur Posted December 19, 2018 Report Share Posted December 19, 2018 Всем доброго времени суток! На сайте есть отдельная страница с отзывами к товарам, на эту страницу валятся все отзывы с различных товарных карточек. Выглядит это так: Задача состоит в том, чтобы немного модернизировать вывод информации, т.е. к отзыву добавить фото товара, наименование товара, вот как здесь: Модуль отвечающий за комментарии connents.tpl выглядит вот так: {* Список записей блога *}{* Канонический адрес страницы *}{$canonical="/otzyvy" scope=parent}<!-- Заголовок /--><h1>{$page->name}</h1><p> </p>{include file='pagination.tpl'} <!-- Отзывы /--><div id="item"><div class="block reviews"><div id="reviewlist"> {foreach $comments as $comment} <div id="bx_{$comment->id}" class="hreview"> <p class="review-meta"> <span class="dtreviewed">{$comment->date|date}, {$comment->date|time}<span title="{$comment->date|date}" class="value-title"></span></span> <span class="sep">|</span> <span class="reviewer">{$comment->name|escape}</span> написал(а): {if !$comment->approved}<span class="sep">- ожидает модерации</span>{/if}</p> <p class="description">{$comment->text|escape|nl2br}</p> <p><a href="{$comment->purl}">Отзыв на странице товара</a></p> </div> {/foreach}</div></div></div><!-- Отзывы #End /--> {include file='pagination.tpl'} Я так понимаю, что в него нужно добавить определенные строки по выводу необходимых полей, но я не программист, поэтому и обращаюсь к вам за помощью. Quote Link to post Share on other sites
question Posted January 13, 2019 Report Share Posted January 13, 2019 Интересная вещь. Сделаю-ка я пожалуй и себе отдельную страницу с отзывами.Страницу добавлю в закладки, завтра посмотрю, как вывести к нужному товару его картинку, и хватит ли моих знаний. А пока я занят, попробуйте куда-нибудь вставить такой код {foreach $last_comments as $comment} {$comment->name|escape} {$comment->url} {$comment->product} {$comment->product->image} {/foreach} Должен вывести url адрес товара, его имя и изображение (изображение вряд ли, но попробуйте). Quote Link to post Share on other sites
Yurinur Posted January 13, 2019 Author Report Share Posted January 13, 2019 Код вставляю, ничего не меняется. Quote Link to post Share on other sites
question Posted January 14, 2019 Report Share Posted January 14, 2019 Для вывода изображения вам надо будет редактировать api/Comments.php, конкретно это обращение к базе if($filter['type'] == 'product') { $products_fields = ', p.url, p.name product'; $products_join = 'INNER JOIN __products p ON c.object_id=p.id'; } В таблице s_products нет изображений, нужно запросить из s_images, где тот же idБез этого вам доступен {$comment->url} вместо вашего {$comment->purl}, непонятно откуда взявшегося. Quote Link to post Share on other sites
Noxter Posted January 14, 2019 Report Share Posted January 14, 2019 Для вывода изображения вам надо будет редактировать api/Comments.php, конкретно это обращение к базе if($filter['type'] == 'product') { $products_fields = ', p.url, p.name product'; $products_join = 'INNER JOIN __products p ON c.object_id=p.id'; } В таблице s_products нет изображений, нужно запросить из s_images, где тот же idБез этого вам доступен {$comment->url} вместо вашего {$comment->purl}, непонятно откуда взявшегося.Так делать не стоит.Нужно в контроллере привязать сущность изображений к сущности комментариев, смотрите как это это сделано сущностью товаров.Удачи! Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 (edited) удалено Edited January 24, 2019 by question Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Очень странно. Вот рабочий SQL запрос, который выводит комментарии с картинками. SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved, i.filename as image FROM s_comments c, s_images i WHERE i.product_id = c.id ORDER BY i.position ASC Но перенеся это в код $query = $this->db->placehold("SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved, i.filename as image $products_fields FROM __comments c, __images i $products_join WHERE i.product_id = c.id $object_id_filter $type_filter $keyword_filter $approved_filter ORDER BY id $sort $sql_limit"); Ничего не выводит. Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 (edited) Всё дело в том, что теперь скрипт формирует следующий запрос SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved, i.filename as image , p.url, p.name product FROM s_comments c, s_images i INNER JOIN s_products p ON c.object_id=p.id WHERE i.product_id = c.id AND c.type='product' AND (c.approved=1 ) ORDER BY id DESC Какая тут допущена ошибка, мне непонятно. Исправив ошибку, можно получить image товара, к которому оставлен комментарий.Помогите найти ошибку Edited January 24, 2019 by question Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Проблема здесь именно в части INNER JOIN s_products p ON c.object_id=p.id MySQL не понимает, что такое c.object_id:Неизвестный столбец 'c.id' в 'on clause' Quote Link to post Share on other sites
phukortsin Posted January 24, 2019 Report Share Posted January 24, 2019 Пробуйте SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved, i.filename as image , p.url, p.name product FROM s_comments c INNER JOIN s_products p ON c.object_id=p.id, s_images i WHERE i.product_id = c.id AND c.type='product' AND (c.approved=1 ) ORDER BY id DESC Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Без INNER JOIN этот запрос выглядел бы вот так SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved, p.url, p.name product, p.id, i.filename FROM s_comments c, s_images i, s_products p where p.id = c.object_id AND i.product_id = c.object_id AND c.type='product' AND (c.approved=1 ) ORDER BY c.id DESC Он работает. Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Пробуйте SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.text, c.approved, i.filename as image , p.url, p.name product FROM s_comments c INNER JOIN s_products p ON c.object_id=p.id, s_images i WHERE i.product_id = c.id AND c.type='product' AND (c.approved=1 ) ORDER BY id DESC Ура, работает! Спасибо. Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Всё бы хорошо, но в MySQL выводится нужное количество строк, а при выводе всех комментариев выводится комментарий для каждого изображения товара. Например, будет три изображения у товара, выведется 3 одинаковых комментария с тремя разными картинками.Временно исправил (вроде бы исправил) ситуацию, указав в sql WHERE i.product_id = c.object_id AND i.position=0 Но это лишь временно, т.к. position может начинаться с 1. Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 (edited) SELECT DISTINCT не помогветMIN (i.position) показывает только один комментарий.WHERE i.product_id = c.object_id AND i.position=0 - костыль.GROUP BY i.position HAVING COUNT(*)=1 выдаёт всего один комментарий несколько раз (столько, сколько в нём встречается изображений) Edited January 24, 2019 by question Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Дошло. Комментарий должен быть уникальным. Значит в конце так GROUP BY c.id ORDER BY id $sort $sql_limit Гуру, правильно? Работает, вроде бы. Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Итого comments.php у меня такой require_once('simpla.php'); class Comments extends simpla { public function get_comment($id) { $query = $this->db->placehold("SELECT c.id, c.object_id, c.name, c.ip, c.type, c.text, c.date, c.approved FROM __comments c WHERE id=? LIMIT 1", intval($id)); if($this->db->query($query)) return $this->db->result(); else return false; } public function get_comments($filter = array()) { $limit = 0; $page = 1; $object_id_filter = ''; $type_filter = ''; $keyword_filter = ''; $approved_filter = ''; $products_fields = ''; $products_join = ''; if(!empty($filter['type'])) if($filter['type'] == 'product') { $products_fields = ', p.url, p.name product'; $products_join = 'INNER JOIN __products p ON c.object_id = p.id, n_images i'; } elseif($filter['type'] == 'blog') { $products_fields = ', b.url, b.name product'; $products_join = 'INNER JOIN __blog b ON c.object_id=b.id'; } if(isset($filter['limit'])) $limit = max(1, intval($filter['limit'])); if(isset($filter['page'])) $page = max(1, intval($filter['page'])); if(isset($filter['ip'])) $ip = $this->db->placehold("OR c.ip=?", $filter['ip']); if(isset($filter['approved'])) $approved_filter = $this->db->placehold("AND (c.approved=? $ip)", intval($filter['approved'])); if($limit) $sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit); else $sql_limit = ''; if(!empty($filter['object_id'])) $object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']); if(!empty($filter['type'])) $type_filter = $this->db->placehold('AND c.type=?', $filter['type']); if(!empty($filter['keyword'])) { $keywords = explode(' ', $filter['keyword']); foreach($keywords as $keyword) $keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR c.text LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" '); } $sort='DESC'; $query = $this->db->placehold("SELECT c.id, c.object_id, c.ip, c.name, c.text, c.type, c.date, c.approved, i.filename as image $products_fields FROM __comments c $products_join WHERE i.product_id = c.object_id $object_id_filter $type_filter $keyword_filter $approved_filter GROUP BY c.id ORDER BY id $sort $sql_limit"); $this->db->query($query); return $this->db->results(); } public function count_comments($filter = array()) { $object_id_filter = ''; $type_filter = ''; $approved_filter = ''; $keyword_filter = ''; if(!empty($filter['object_id'])) $object_id_filter = $this->db->placehold('AND c.object_id in(?@)', (array)$filter['object_id']); if(!empty($filter['type'])) $type_filter = $this->db->placehold('AND c.type=?', $filter['type']); if(isset($filter['approved'])) $approved_filter = $this->db->placehold('AND c.approved=?', intval($filter['approved'])); if(!empty($filter['keyword'])) { $keywords = explode(' ', $filter['keyword']); foreach($keywords as $keyword) $keyword_filter .= $this->db->placehold('AND c.name LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" OR c.text LIKE "%'.mysql_real_escape_string(trim($keyword)).'%" '); } $query = $this->db->placehold("SELECT count(distinct c.id) as count FROM __comments c WHERE 1 $object_id_filter $type_filter $keyword_filter $approved_filter", $this->settings->date_format); $this->db->query($query); return $this->db->result('count'); } public function add_comment($comment) { $query = $this->db->placehold('INSERT INTO __comments SET ?%, date = NOW()', $comment); if(!$this->db->query($query)) return false; $id = $this->db->insert_id(); return $id; } public function update_comment($id, $comment) { $date_query = ''; if(isset($comment->date)) { $date = $comment->date; unset($comment->date); $date_query = $this->db->placehold(', date=STR_TO_DATE(?, ?)', $date, $this->settings->date_format); } $query = $this->db->placehold("UPDATE __comments SET ?% $date_query WHERE id in(?@) LIMIT 1", $comment, (array)$id); $this->db->query($query); return $id; } public function delete_comment($id) { if(!empty($id)) { $query = $this->db->placehold("DELETE FROM __comments WHERE id=? LIMIT 1", intval($id)); $this->db->query($query); } } } Теперь вывод комментария: {get_comments var=last_comments type='product'} {foreach $last_comments as $comment} {$comment->image} {$comment->name} {$comment->url} {$comment->product} {$comment->date|date} {$comment->text} {/foreach} Проверяйте. Quote Link to post Share on other sites
question Posted January 24, 2019 Report Share Posted January 24, 2019 Демо http://tetramebel.ru/отзывыОстальной функционал сайта работает через пень-колоду, но задача ТС, как мне кажется, решена. Quote Link to post Share on other sites
question Posted February 3, 2019 Report Share Posted February 3, 2019 В моём коде допущена ошибка, в админке отзывы не отображались. Только вчера заметил. Quote Link to post Share on other sites
WIXVW Posted February 8, 2019 Report Share Posted February 8, 2019 Привет, а можно полный код вывода отзывов для товаров на отдельную страницу уже с фото и названием?Лазил по форуму, находил пару веток с выводом отзывов на отдельной странице, но по ним ничего не вышло( Quote Link to post Share on other sites
question Posted February 9, 2019 Report Share Posted February 9, 2019 Не могу полную инструкцию сделать, мне на это очень много времени понадобится, тем более, когда скрипт уже отличается от оригинального.Все правки в теме выкладывал. Quote Link to post Share on other sites
question Posted February 9, 2019 Report Share Posted February 9, 2019 Мой код вывода такой (у вас скорей всего не будет работать): {if $page->id == 172} {get_comments var=last_comments type='product'} {foreach $last_comments as $comment} <img src="{$comment->image|resize:70:70}"> <p>{$comment->name|escape}</p> <a href="{$comment->category_url}/{$comment->url}.html">{$comment->product}</a> <i>{$comment->date|date}</i> {$comment->text} {/foreach} {/if} Но принцип, думаю, поймёте. Quote Link to post Share on other sites
MaLeN Posted September 4, 2019 Report Share Posted September 4, 2019 А как вывести комментарии в аккаунте пользователя? Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.