我有三个表:(为了简单起见,我只显示相关字段)
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_name
和 last_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_id
是 articles
和 comments
表的外键,因为您说过作者和评论者 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/