根据类别和颜色搜索结果

时间:2013-09-23 11:14:44

标签: php mysql codeigniter search

我有4个mysql表如下..

产品(id,sku,name,color_id,description,excerpt)

颜色(color_name,color_id)

类别(categ_name,categ_id)

Product_Categories (pid,cid)

现在我想执行搜索操作。目前我的搜索查询基于产品ID,sku,description或color_id。

我的查询在codeigniter中如下....

$color_id   =   0;
        $this->db->select('color_id');
        $this->db->where('LOWER(color_name)',strtolower($term));
        $color_row  =   $this->db->get('product_colors')->row();
        if($color_row)
            $color_id   =   $color_row->color_id;

$this->db->select('*, LEAST(IFNULL(NULLIF(saleprice, 0), price), price) as sort_price', false);
        //this one gets just the ones we need.
        $this->db->where('enabled', 1);
        $this->db->where('(name LIKE "%'.$term.'%" OR description LIKE "%'.$term.'%" OR excerpt LIKE "%'.$term.'%" OR sku LIKE "%'.$term.'%" OR color='.$color_id.')');

这个工作绝对正常。但我也想在类别的基础上搜索。例如,我想搜索“Red Shoes”,其中红色是颜色,鞋子是类别名称。

请告诉我如何为此构建查询。

这将是一个很大的帮助。

感谢!!!

3 个答案:

答案 0 :(得分:1)

通过加入所有表格来试试这个

$term=$_POST['your search field name'];
$keyword=explode(" ",$term);
$this->db->select('p.*');
$this->db->from('Products p');
$this->db->join('Product_Categories pc', 'p.id = pc.pid','LEFT');
$this->db->join('Categories c', 'pc.cid = c.categ_id','LEFT');
$this->db->join('Colors co', 'p.color_id = co.color_id','LEFT');
$this->db->where('p.enabled', 1);

foreach($keyword as $k){
$this->db->or_where('p.id =', $k);//or_where
$this->db->like('p.sku', $k);
$this->db->like('p.description', $k);//or_like
$this->db->like('co.color_name', $k);
$this->db->like('c.categ_name', $k);

}

$this->db->group_by("p.id"); 

Active Record Class

答案 1 :(得分:0)

SELECT * FROM PRODUCTS JOIN 
Product_Categories ON PRODUCTS.id = Product_Categories.pid
JOIN Categories on Categories.categ_id = Product_Categories.cid
JOIN Colors ON Colors.color_id = Products.color_id
WHERE categ_name = 'Shoes' AND Colors='Red';

答案 2 :(得分:0)

首先获取类别名称  $ categ_name = $ categ_row-categ_name;  $ color_name = $ color_row-color_name;

在条件中将Colors.color_name设置为'$ color_name',将Categories.categ_name设置为'$ categ_name'