【问题标题】:Codeigniter Active Record join and loop only returning one resultCodeigniter Active Record 加入和循环只返回一个结果
【发布时间】:2011-07-31 14:19:57
【问题描述】:

我正在使用 Codeigniter 和活动记录创建一个简单的论坛脚本。

我想使用这个函数来获取所有线程及其各自的回复计数以传回我的控制器。

使用下面的脚本,我只得到数组中返回的第一个线程(及其回复数),而不是我的所有线程。

为什么会这样,如何解决?

function get_threads($id){

    $this->load->database();

    $this->db->select('title,ID,COUNT(replies.threadID) as replies');
    $this->db->from('threads');
    $this->db->join('replies', 'threads.ID = replies.threadID');

    $query=$this->db->where('forum', $id);
    $query=$this->db->get();

    $data=$query->result_array();

    return $data;
}

【问题讨论】:

  • 每个话题都有回复吗?否则你应该使用左连接来获得零回复线程
  • 每个线程可以有任意数量的回复。你能澄清一下吗?

标签: codeigniter activerecord loops join


【解决方案1】:

如果您留下加入线程和回复,即使没有回复,您也会得到每个线程,请记住,当您使用聚合函数 (COUNT) 时,您需要对行进行分组:

$this->load->database();

$this->db->select('title,ID,COUNT(replies.threadID) as replies');
$this->db->from('threads');
$this->db->join('replies', 'threads.ID = replies.threadID','left');
$this->db->group_by('threads.title, threads.ID');
$this->db->where('forum', $id);

$query = $this->db->get();

如果没有找到回复,COUNT 将返回 0

简要说明:

你想知道每个线程的回复数,那么你需要告诉MYSQL什么时候停止计数并重置计数器。或者更好的是,您必须告诉 MYSQL 如何对数据进行分组,聚合函数(此处为 COUNT)将应用于每个组。 谷歌“按 mysql 分组”以获取更多信息

【讨论】:

  • 完美运行 - 不同之处在于 group_by 行。您能否澄清为什么需要这样做/它做了什么?非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2021-09-24
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多