【问题标题】:Yii CListView and conflict with MVC principlesYii CListView 与 MVC 原则冲突
【发布时间】:2012-10-04 21:00:47
【问题描述】:

Yii 大师!

我们有一个博客。博客有一个包含作者列表的页面。作者存储在 AUTHOR 表中。我使用了基本的 Yii-widget CListView 来展示它:

public function actionIndex() {
    $dataProvider = new CActiveDataProvider('Author');
    $this->render('index', array(
        'dataProvider' => $dataProvider,
    ));
}

比views/author/view.php:

$this->widget('zii.widgets.CListView', array(
    'dataProvider' => $dataProvider,
    'itemView' => '_view',
));

但是除了关于作者的信息之外,这个列表还必须包含每个作者的五篇随机相关文章的网址。文章标题存储在 ARTICLE 表中。现在我使用一个丑陋的解决方案(views/authors/_view.php):

<ul class="experts-node-articles-list">
    <?php $authorArticles = Article::model()->findAllByAttributes(
        array('author_id' => $data->id), 
        array('limit' => '5'
    )); ?>
    <?php foreach ($authorArticles as $item) : ?>
    <li><a href="#"><?php echo CHtml::encode($item->title); ?></a></li>
    <?php endforeach; ?>
</ul>

因为在视图中调用模型,所以很难看。这是与 MVC 原则恕我直言的冲突。我可以以真正的 MVC 方式做到这一点吗?我怀疑它可以通过模型关系和范围来完成......但不幸的是我不知道如何。

【问题讨论】:

    标签: php yii


    【解决方案1】:

    1) 在 Author 模型中创建关系。 (您可以像这样添加/更新relations() 方法)

    public function relations()
    {
        return array(
            .....
            'randomArticles' => array(
                self::HAS_MANY, 
                'Article', 
                'author_id',
                'limit' => 5,
                'order' => 'RAND()',
            ),
            .....
        );
    }
    

    2) 你的数据提供者必须是这样的。

    $dataProvider = new CActiveDataProvider('Author', array(
        'criteria'=>array(
            'with'=>array('randomArticles'),
        ),
    ));
    

    3) 在你的视图 (views/authors/_view.php) 中,你可以做这样的事情。

    foreach($data->randomArticles as $article ) {
        // display $article info, something like below
        $this->renderPartial('_artical_info', array('article' => $article));
    }
    

    这样可以节省大量的 sql 查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 2011-12-08
      • 2018-05-13
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多