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

标签 php codeigniter join

我正在使用简单的联接从两个数据库中提取数据。这是模型中的连接:

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;
}

我想要的显示方法将在表格中,所以我开始像这样使用:

foreach($comm_control as $row){

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

我的问题是来自 comments.id 的数据显示。将 comment.id 添加到表行中的正确格式是什么?我需要两个表中的 ID 以便在表中进一步显示、编辑和删除。此时我得到的“comment.id”唯一显示是单词 id。

如有任何帮助,我们将不胜感激。

最佳答案

好吧,我想你需要做的是为评论表中的 id 字段设置一个别名:

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;
}

然后您可以将comments.id字段引用为简单的$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;当您连接两个具有相同列名的表时,就会出现问题;它变得含糊不清,计算机将不知道你在引用什么。

关于php - 在 Codeigniter 中显示来自连接的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4702030/

相关文章:

php - 在 URL 中保留一个 GET 变量

javascript - jQuery 中的自动完成只是...停止工作?

codeigniter - 在MVC中,处理和解析数据的应该是Model还是Controller?

php - 使用 codeigniter 在搜索表单中搜索后无法从数据库中获取行数据

php - 使用 : PHP, Ubuntu、EC2 Amazon Web Services 将图像加载到 DynamoDB

PHP:变量函数名(函数指针)调用;如何告诉 IDE 我的函数被调用了?

r - 使用 R 更正/整理数据

Mysql:在列中计数(带连接)

mysql - 连接多个匹配值的表

php - 在带有搜索字段的查询中包含 <SELECT>