php - 在 Codeigniter 的 View / Controller 中使用模型

标签 php codeigniter

我使用 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/

相关文章:

php - 在图像旁边放置文本

php - 使用 mysql 进行计算,我在计算时遇到了麻烦

php - CodeIgniter 中的 SQL 查询

php - CodeIgniter、Filter、Trim、Stripslashes、Strip_tags 和清理并替换 1 个函数中的坏字符?

php - 我应该如何为 CodeIgniter 选择身份验证库?

javascript - 简单的ajax调用数据库来验证电子邮件php codeigniter

php - 在文本编辑器中使用 mysql_connect 时遇到问题

php - 修改需要唯一的ID码! Opencart OCMOD

php - 在php中从EDT转换为GMT+05.30时区以在mysql数据库中输入时间戳

php - CodeIgniter 中的特征