如何根据opencart中的类别对购物车页面上的产品进行分组?

时间:2013-12-07 10:44:53

标签: php mysql opencart

我们想根据类别在购物车页面中获取数据,根据编号对总金额进行折扣。同类产品。

在模型文件中

public function getCategory($data)
{   
    $sql = "SELECT category_id FROM " . DB_PREFIX . "Product_to_category where product_id='".$data."'";
    $query = $this->db->query($sql);
    foreach($query as $key=>$value)
    {       
        //print_r($key); echo "=>"; print_r($value);
        foreach($value as $k=>$v)
        {   
            //echo $k."=>".$v;
            return $k."=".$v;
        }   
    }       
}

在控制器文件/catalog/controller/checkout/cart.php

$r[]=$this->model_discount_cdiscount->getCategory($product['product_id']);

2 个答案:

答案 0 :(得分:1)

您的模型功能错误。

首先,$this->db->query($sql)返回一个包含属性rowrowsnum_rows的对象。因此,您的第一个foreach循环是错误的。

其次,如果您从product_to_ctegory为一个具体产品选择类别ID,您总是需要一组类别ID,因此您必须坚持使用$query->rows属性。而第二个foreach循环对我来说完全没有意义......

所以这应该是你的方法:

public function getCategories($product_id) {   
    $query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "product_to_category WHERE product_id = " . (int)$product_id);
    $categories = array();
    foreach($query->rows as $row) {
        $categories[] = $row['category_id'];
    }
    echo "Product ({$product_id}) is linked to categories with IDs: " . implode(', ', $categories);
}

另请注意SQL查询变量类型转换 - 以避免SQL注入...

虽然我不确定你想通过加载产品的所有类别来实现什么,但我相信我能以正确的方式获得你。无论如何,如果您只选择主(1 st 级别)类别(使用parent_id === 0),它可能对您更有用,因此查询可能如下所示:

$query = $this->db->query("SELECT c.category_id FROM " . DB_PREFIX . "product_to_category ptc LEFT JOIN " . DB_PREFIX . "category c ON c.category_id = ptc.category_id WHERE ptc.product_id = " . (int)$product_id . " AND c.parent_id = 0");

当然,这需要所有产品都正确地链接(嵌套)到类别 - 从顶层到底层(我见过很多实时系统,其中proucts只链接到底层类别.. )。

答案 1 :(得分:1)

////////////// Grouping Same category products into one array //////////////

$category_id = $this->model_discount_cdiscount->getcategory($product['product_id']);

$array_key = $category_id[0]['category_id']; 

if (array_key_exists($array_key, $this->data['discount']))
{

    $this->data['discount'][$array_key]['total'] = $this->data['discount'][$array_key]['total']+(preg_replace("/[^0-9.]/","",$total));
    $this->data['discount'][$array_key]['quantity'] = $this->data['discount'][$array_key]['quantity']+$product['quantity'];
}
else
{
    $this->data['discount'][$array_key] = array(
            'category_name' => $category_id[0]['name'],
            'category_id' => $array_key,
            'total' => (preg_replace("/[^0-9.]/","",$total)),
            'quantity' => $product['quantity'],
            'length' => $product['length']
        );
}

-