我正在尝试在类别页面中添加按畅销产品排序。
为此,我在catalog/controller/product/category.php
控制器中添加了以下代码:
$this->data['sorts'][] = array(
'text' => 'Bestsellers',
'value' => 'bestsellers',
'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . '&sort=bestsellers&order=DESC' . $url)
);
添加此内容后,我可以在排序列表中看到畅销书选项。现在我正在尝试进行数据库查询以完成此排序。我试图克隆现有的排序,如按名称排序(A-z),但因为我是opencart的新手,我无法做到这一点。
请您分享您的想法如何做到这一点?
答案 0 :(得分:2)
我将引导你,查询部分取决于你......
同时修改catalog/model/catalog/product.php
- 方法getProducts($data)
。检查这部分:
$sort_data = array(
'pd.name',
'p.model',
'p.quantity',
'p.price',
'rating',
'p.sort_order',
'p.date_added'
);
并添加您的新排序,例如bestsellers
,所以你最终得到这个数组:
$sort_data = array(
'pd.name',
'p.model',
'p.quantity',
'p.price',
'rating',
'p.sort_order',
'p.date_added',
'bestsellers',
);
现在您必须编辑以if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
开头的下一部分,以便您最终得到:
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
} elseif ($data['sort'] == 'p.price') {
$sql .= " ORDER BY (CASE WHEN special IS NOT NULL THEN special WHEN discount IS NOT NULL THEN discount ELSE p.price END)";
} elseif ($data['sort'] == 'bestsellers') { // <-- YOUR NEW SORTING
$sql .= " ORDER BY <ADD YOUR SORTING QUERY HERE>";
} else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY p.sort_order";
}
添加正确的查询后,而不是<ADD YOUR SORTING QUERY HERE>
您应该完成。
答案 1 :(得分:1)
我做了2次更改并测试了代码以便正常运行:
1) remove the (,) in 'bestsellers',
2) updated the sql code to read:
$sql .= " ORDER BY (SELECT sum(quantity) FROM " . DB_PREFIX . "order_product op where op.product_id=p.product_id GROUP BY p.product_id) ";
这里是catalog / model / catalog / product.php的代码:
$sort_data = array(
'pd.name',
'p.model',
'p.quantity',
'p.price',
'rating',
'p.sort_order',
'p.date_added',
'bestsellers'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
} else if ($data['sort'] == 'p.price') {
$sql .= " ORDER BY (CASE WHEN special IS NOT NULL THEN special WHEN discount IS NOT NULL THEN discount ELSE p.price END)";
} else if ($data['sort'] == 'bestsellers') { // Sorting as suggested by shadyyx
$sql .= " ORDER BY (SELECT sum(quantity) FROM " . DB_PREFIX . "order_product op where op.product_id=p.product_id GROUP BY p.product_id) ";
} else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY p.sort_order";
}
和catalog \ controller \ product \ product.php的代码:
$data = array(
'filter_category_id' => $categories_info['category_id'],
'sort' => 'bestsellers',
'order' => 'DESC'
);
$results = $this->model_catalog_product->getProducts($data);