在Codeigniter中显示联接中的数据 [英] Displaying Data from a Join in 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
我的问题是显示comment.id中的数据.什么是将comment.id添加到表行中的正确格式?我需要两个表中的ID才能在表中进一步显示,编辑和删除.我目前唯一显示的"comment.id"是单词id.
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.
任何帮助将不胜感激.
推荐答案
好的,我想您需要做的是为注释表中的id字段设置一个别名:
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;
}
然后,您可以简单地通过$ row-> comment_id来引用comments.id字段:
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();
实际上,如果'id'列对于注释表是唯一的,则可以只使用$ row-> id;.当您联接具有相同名称的列的表时,会出现问题;它变得模棱两可,并且计算机将不知道您在引用什么.
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.
这篇关于在Codeigniter中显示联接中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!