简体   繁体   English

防止从CodeIgniter的数据库中获取重复数据

[英]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 这是我在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. 可以同时搜索许多类别过滤器,这就是为什么我使用or_where()方法。

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 您可以使用eleminate重复的值distinctgroup by

As you select all fields a group by is better in my opinion. 我认为,当您选择所有字段时, group by会更好。 Example to group by category_id category_id分组的示例

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

You can use group_by to solve this issue 您可以使用group_by解决此问题

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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