dongxun7962 2011-01-15 20:43
浏览 33
已采纳

在Codeigniter中显示来自连接的数据

I am using a simple join to pull data from two databases. This is the join in the model:

function com_control(){
    $this->db->select('*');
    $this->db->from('comments');
    $this->db->join('posts', 'comments.entry_id = posts.id');
    $query = $this->db->get();
    return $query->result;
}

My desired method of display is going to be in a table so I am starting out to use like this:

foreach($comm_control as $row){

   $this->table->add_row(
   $row->entry_id,
   $row->comments.id,
   $row->comment,
   $row->title             
   );      
}//end of foreach

My problem is the display of data from comments.id. What is the proper format to add the comment.id into the table rows? I need the ID from both tables for display, edit and delete further on in the table. The only display I get at this time for "comment.id" is the word id.

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • douludi8413 2011-01-15 20:59
    关注

    Okay, I think what you need to do is set an alias for the id field in the comments table:

    function com_control() {
        $this->db->select('entry_id, comments.id AS comment_id, comment, title');
        $this->db->from('comments');
        $this->db->join('posts', 'comments.entry_id = posts.id');
        $query = $this->db->get();
    
        return $query->result;
    }
    

    Then you can reference the comments.id field as simply $row->comment_id:

    $this->table->set_heading('Entry ID', 'Comment ID', 'Comment', 'Title');
    
    foreach ($comm_control as $row ) {
        $this->table->add_row(
            $row->entry_id,
            $row->comment_id,
            $row->comment,
            $row->title             
        );      
    }
    
    echo $this->table->generate();
    

    Actually if the column 'id' is unique to the comments table, then you could just use $row->id; the problem arises when you are joining tables that both have a column named the same; it becomes ambiguous and the computer won't know what you're referencing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line