如果您想显示来自 2 个表的数据并且您想要的输出不同,我建议您使用 2 个视图。在您的模型中,您应该创建函数来获取所有必要的数据,然后将其传递给控制器。在控制器中,您应该将它们分配给变量并将它们传递给视图。请参见下面的示例。
tbl_articles
article_id | article_title | article_text
1 Title of article Sample text of article
2 Title of article no. 2 sample text of article no. 2
tbl_reviews
review_id | review_title | review_text | review_rate
1 Title of review Sample text 5
2 Title of review no. 2 Sample text 2 4
控制器:
<?php
class Site extends CI_Controller {
public function articles()
{
$this->load->model('main_model');
$data['articles'] = $this->main_model->get_articles();
$this->load->view('articles', $data);
}
public function reviews()
{
$this->load->model('main_model');
$data['articles'] = $this->main_model->get_reviews();
$this->load->view('reviews', $data);
}
}
模型:
<?php
class Main_model extends CI_Model {
public function get_articles()
{
return $this->db->select('article_id, article_title, article_text')
->get('tbl_articles')
->result();
}
public function get_reviews ()
{
return $this->db->select('review_id, review_title, review_text, review_rate')
->get('tbl_reviews')
->result();
}
}
意见:
- 文章视图:
<?php
if (count($articles) == 0):
echo 'Nothing to show';
else:
foreach($articles as $article):
?>
<h1><?php echo $article->article_title; ?></h1>
<p><?php echo $article->article_text; ?></p>
<?php
endforeach;
endif;
?>
- 评论视图:
<?php
if (count($reviews) == 0):
echo 'Nothing to show';
else:
foreach($reviews as $ review):
?>
<h1><?php echo $ review -> review _title; ?></h1>
<p><?php echo $ review -> review text; ?></p>
<p>Rate of user: <?php echo review->review_rate; ?></p>
<?php
endforeach;
endif;
?>