2

我使用 codeigniter 进行 Web 开发。随着我对它的了解越来越多,我发现了更多我无法获得正确逻辑实现的问题。

我有一个article_controller.php和一个观点article.php。我正在尝试在页面上显示所有文章标题。(此代码仅用于测试目的)。

假设我有另一个名为的表images,其中包含文章中使用的所有图像。那么我可以在视图上使用images_m.php模型吗?article.php

Article_Controller.php

$data['articles'] = $this->article_m->get(); //gets all of the articles 
$this->load->view('articles',$data);

文章.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;

The code works perfectly fine. I have used similar code in a number of websites. But the main issue is, I have read that it is not a good idea to use models in views. Use models in controllers instead.

So how can I fetch the images for a particular article in a controller.

4

2 回答 2

3

在您的控制器中获取图像并将图像对象与每个文章对象合并并将其传递给查看

$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);

确保您已将images_m模型加载到控制器中

于 2013-09-06T20:44:32.360 回答
2

像这样的东西(伪代码)可能会起作用:

控制器:

$articles = $this->article_m->get();
$images = array();

foreach($articles as $article):
    $images[$article->id] = array();

    $article_images = $this->images_m->get_by(array('article_id'=>$article->id));
    foreach($article_images as $image):
        $images[$article->id][] = './uploads/'.$image->filename;
    endforeach; 
endforeach;

$data['articles'] = $articles;
$data['images'] = $images;

$this->load->view('articles',$data);

看法:

foreach($articles as $article):
    echo $article->title;

    foreach($images[$article->id] as $image):
        echo "<img src='$image'/>";
    endforeach; 

endforeach;

基本上只是做你在视图中做的同样的工作,然后在控制器中做。然后把它扔到$data数组中并发送到视图中。


编辑:我建议查看@dianuj 的答案:)

于 2013-09-06T20:43:45.983 回答