我使用 codeigniter 进行 Web 开发。随着我学习的深入,我发现了更多无法得到正确逻辑实现的问题。
我有一个 article_controller.php
和一个 View article.php
。我正在尝试在页面上显示所有文章标题。 (此代码仅用于测试目的)。
假设我有另一个名为 images
的表,其中包含文章中使用的所有图像。那么我可以在 article.php
View 上使用 images_m.php
模型吗?
Article_Controller.php
$data['articles'] = $this->article_m->get(); //gets all of the articles
$this->load->view('articles',$data);
Article.php
foreach($articles as $article):
echo $article->title;
$images = $this->images_m->get_by(array('article_id'=>$article->id)); //gets all the images for current article
foreach(images as $image):
echo "<img src='./uploads/".$image->filename ."'/>";
endforeach;
endforeach;
代码运行得非常好。我在许多网站中使用过类似的代码。
但主要问题是,我读到在 View 中使用模型并不是一个好主意。请改用 Controller
中的模型
。
那么如何在 Controller 中获取特定文章的图像。
最佳答案
在 Controller 中获取图像并将图像对象与每个文章对象合并并将其传递给 View
$articles= $this->article_m->get(); //gets all of the articles
foreach($articles as $article):
$article->article_images = $this->images_m->get_by(array('article_id'=>$article->id)); //gets all the images for current article
endforeach;
$data['articles']=$articles;
$this->load->view('articles',$data);
确保您已在 Controller 中加载 images_m
模型
关于php - 在 Codeigniter 的 View / Controller 中使用模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18666031/