表连接:无法显示我想要的数据

时间:2013-05-02 02:46:28

标签: php codeigniter join

如果我有这样的表:

ID | Title | Topic      | Summary    
1   |   A   | Technology | ...    
2  |   B   | Health     | ...    
3  |   C   | Sport      | ...

这是我的CI_Model:

function show($limit, $offset)
    {
        $this->db->select('document.id, document.title, document.summary, document.id_topic AS topic');
        $this->db->from('document');
        $this->db->join('topic', 'topic.id_topic = document.id_topic');
        $this->db->limit($limit, $offset);
        $this->db->order_by('id', 'asc');
        return $this->db->get()->result();
    }

这是我的控制器:

            $docdata = $this->Trainingmodel->show($this->limit, $offset);
        ...
        $this->table->set_heading('ID', 'Title', 'Topic', 'Summary');
        foreach ($docdata as $doc)
        {
            $this->table->add_row($doc->id, $doc->title, $doc->topic, $doc->summary);                                                                                               
        }

显然主题显示的是id,而不是名字。 例如:

ID | Title | Topic      | Summary    
1   |   A   | 1 | ...    
2  |   B   | 2  | ...    
3  |   C   | 3  | ...

我该怎么办?我想显示主题的名称,而不是主题的ID。

3 个答案:

答案 0 :(得分:1)

$this->db->select('document.id, document.title, document.summary, topic.topic');
$this->db->from('document');
$this->db->join('topic', 'topic.id = document.id_topic');

答案 1 :(得分:1)

查看您在其他答案中发表评论的表格结构,我认为您topic.topic中的select()topic.id = document.id_topic中的join() -

$this->db->select('document.id, document.title, document.summary, topic.topic');
$this->db->from('document');
$this->db->join('topic', 'topic.id = document.id_topic');

答案 2 :(得分:0)

也许是因为document.id_topic

$this->db->select('document.id, document.title, document.summary, document.id_topic AS topic');

应该是document.topic还是document.name_topic