mysql - 如何从 CodeIgniter 中的多个表中进行选择

标签 mysql activerecord codeigniter select join

我有三个表:(为了简单起见,我只显示相关字段)

Articles (id, title, text, author)
Comments (id, article_id, text, author)
Users (user_id, user_type, first_name, last_name, email, password)

articles表中,由于一个作者可以有多篇文章,所以我只存储users表中作者的user_id,并且我对 comments 表执行相同操作。

我的问题是,当我在articles_model中运行ActiveRecord查询以获取所有文章以及与该文章相关的评论,然后使用$row->author在我的 View 中回显作者时,我只获取作者的user_id,即1、2、3等。

如何在同一查询中进入 users 表(不同的表)并获取作者实际的 first_namelast_name 并返回那?

这是我的代码:

Controller :

$data['articles'] = $this->getArticles();
$this->load->view('articles_view', $data);

function getArticles() {
  $this->load->model('articles_model');
  $articles = $this->articles_model->getAllArticles();
  return $articles;
}

文章模型:

function getAllArticles() {
  $this->db->where('id', $this->uri->segment(3));
  $query = $this->db->get('articles');
  return $query;
}

文章 View :

<?php foreach($articles->result() as $row) { ?>
<?php echo $row->author ?>
<?php echo $row->text ?>
<?php } ?>

我还有很多其他字段,但为了简单起见,这是一个极其精简的版本。

如果我回显上面的$row->author,我只会获得 user_id。我需要从 users 表中获取用户名。当然,我不必再执行另一个单独的函数调用并将更多信息传递到 View 中。这里的任何帮助将不胜感激,并且实际上会为我打开一个世界:)

最佳答案

试试这个(或者只是有一个想法):

我假设您的 users 表中的 user_idarticlescomments 表的外键,因为您说过作者和评论者 user_id 存储在 users 表中。

在您的 Controller 上:

$data['articles'] = $this->getArticles(); 
$this->load->view('articles_view', $data);

function getArticles() { 
   $this->load->model('articles_model'); 
   $articles = $this->articles_model->getArticlesById(); 
   return $articles; 
}

在您的型号上:

// this will get the article of a certain author   
function getArticlesById()
{
   $this->db->where('id', $this->uri->segment(3)); 
   $q = $this->db->get('articles'); 
   if($q->num_rows() > 0)
   {
       $q = $q->row_array();
       $result = $this->getCommentsAndAuthors($row);
       return $result;
   }
   return 0;
}

// this will get the comments of each articles of the author and the author of the comments
function getCommentsAndAuthors($row)
{
    $result = $data = array();

    $this->db->select('c.*, u.firstname, u.lastname');
    $this->db->from('users u');
    $this->db->where('u.id', $row['user_id']);
    $this->db->join('comments c', 'c.id = u.id');
    $q = $this->db->get();
    foreach($q->result_array() as $col)
    {
        $data[] = $col;
    }
    $result['article'] = $row;
    $result['comments'] = $data;
    return $result;
}

我不确定它是否有效,但这就是想法。

关于mysql - 如何从 CodeIgniter 中的多个表中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3454922/

相关文章:

mysql - 如果一列有多个逗号分隔值,我如何过滤 mysql 数据?

mysql - 查找关联模型中日期范围内的差距 | Rails 上的 Ruby

php - Codeigniter URL 路由 - SEO 问题

java - Google Web Toolkit (GWT)、GAE 和 Google Cloud SQL (mySQL) 中的时区

php - 使用自定义 SQL 的学说子查询

mysql - 子查询不提供输出

ruby-on-rails - 如果数据库为空,则处理 ActiveRecord 错误

ruby-on-rails - 这是 Rails 验证线程安全的吗

php - Codeigniter 电子邮件 - `554 SMTP 同步错误

codeigniter - 文件从休息客户端上传到休息服务器