首页 > 解决方案 > Codeigniter:查询结果不重复字段

问题描述

我的模型中有这个查询:

public function getById(int $id): ?array
    {
        $query = $this->db->select(['id', 'docent_id', 'date', 'start_at', 'end_at'])
                ->where('docent_id', $id)
                ->where('delete_date is null')
                ->get('Agenda');
        $res = $query->result();

        return $res;
    }

我的问题在我的数据库中,我有类似的东西:

| id | docent_id | date       | start_at | end_at
| 1  |    1      | 2020-05-04 |   09:00  | 10:00
| 2  |    1      | 2020-05-04 |   10:00  | 11:00

所以这个结果打印了我相同的 docent_id 两个字段。我会将答案分组,以便日期不会重复两次,这样它就可以为同一个讲解员提供一个相同的结果,具有相同的日期和不同的开始和结束时间。

我能怎么做?谢谢

标签: phpcodeigniter

解决方案


我想你需要的是GROUP BY. docent_id以下查询仅在所有 4( 、date和) 的组合不start_at同时才会显示数据end_at。看看这是否对您有帮助。

$query = $this->db->select(['id', 'docent_id', 'date', 'start_at', 'end_at'])
                  ->where('docent_id', $id)
                  ->where('delete_date is null')
                  ->group_by(array("docent_id", "date", "start_at", "end_at"))
                  ->get('Agenda');

$res = $query->result();

推荐阅读