简体   繁体   中英

Prevent getting a duppicate data from the database in CodeIgniter

I'm trying to get data from the database filtered by some categories

This is my code in CodeIgniter

$this->db
    ->select('*')
    ->from($this->table)
    ->join('sites','sites.id = categories_by_site.site_id')
    ->where('categories_by_site.category_id', $categories[0])
    ->or_where('categories_by_site.category_id', $categories[1])
    ->order_by('id', 'ASC')
    ->get()
    ->result();

I simplify my code for the sake of this question, the above query take the categories as a search filter and used it to get result from the database.

There can be many categories filter to search at the same time, that's why I am using or_where() method.

The problem with this, when I got the result data, it has duplicate row of entries in object array.

Anyone can suggest how to prevent from getting a duppicate data from the database using above query?

Thanks

You can eleminate duplicate values using distinct or group by

As you select all fields a group by is better in my opinion. Example to group by category_id

$this->db->group_by('category_id');

You can use group_by to solve this issue

Replace your code with

$this->db
    ->select('*')
    ->from($this->table)
    ->join('sites','sites.id = categories_by_site.site_id')
    ->where('categories_by_site.category_id', $categories[0])
    ->or_where('categories_by_site.category_id', $categories[1])
    ->order_by('id', 'ASC')
    ->group_by('categories_by_site.category_id')
    ->get()
    ->result();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM