开发者

Displaying Data from a Join in Codeigniter

开发者 https://www.devze.com 2023-02-04 05:02 出处:网络
I am using a simple join to pull data from two databases. This is the join in the model: function com_control(){

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(
   $ro开发者_运维问答w->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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消