Reputation: 3716
shops table:
+--+-------+--------+
|id|name |date |
+--+-------+--------+
|1 |x |March 10|
+--+-------+--------+
|2 |y |March 10|
+--+-------+--------+
category table :
+--+-------+
|id|title |
+--+-------+
|1 |tools |
+--+-------+
|2 |foods |
+--+-------+
shop categories table (shop_cats):
+--+-------+--------+
|id|shop_id|cat_id |
+--+-------+--------+
|1 |1 |1 |
+--+-------+--------+
|2 |1 |2 |
+--+-------+--------+
i want to get shops by category (categories are stored in the $cat array)
$this->db->select('shops.*');
$this->db->from('shops');
if(!empty($cat))
{
$this->db->join('shop_cats' , 'shop_cats.shop_id = shops.id' );
$this->db->where_in('shop_cats.cat_id' , $cat);
}
$this->db->limit($limit , $offset);
$res = $this->db->get();
my problem is it returns duplicate results for example in this table
+--+-------+--------+
|id|shop_id|cat_id |
+--+-------+--------+
|1 |1 |1 |
+--+-------+--------+
|2 |1 |2 |
+--+-------+--------+
if i want shops with (1,2) category i get shop with id = 1 , twice . i want it to return each shop only once without any duplicate .
i've tried to use group by
if(!empty($cat))
{
$this->db->join('shop_cats' , 'shop_cats.shop_id = shops.id' );
$this->db->group_by('shop_cats.shop_id');
$this->db->where_in('shop_cats.cat_id' , $cat);
}
it didn't work , i've also tried
if(!empty($cat))
{ $this->db->select('DISTINCT shop_cats.shop_id');
$this->db->join('shop_cats' , 'shop_cats.shop_id = shops.id' );
$this->db->where_in('shop_cats.cat_id' , $cat);
}
but i get syntax error !
Upvotes: 1
Views: 161
Reputation: 1429
Try
$this->db->distinct('shops.*');
$this->db->from('shops');
$this->db->join('shop_cats', 'shop_cats.shop_id = shops.id', 'left');
$this->db->where('shop_cats.cat_id', $cat);
$this->db->limit($limit , $offset);
$res = $this->db->get();
Upvotes: 1