【问题标题】:Merging an array with DataProvider data items将数组与 DataProvider 数据项合并
【发布时间】:2013-08-07 17:49:14
【问题描述】:

我的 Yii 应用程序中有 2 个表; 类别项目

Category
- id
- name

Item
- id
- category_id
- name

我想做的是获取 Category 表中的项目列表,然后计算 Item 表中每个类别的项目数。

我正在使用 CActiveDataProvider 检索 Category 表中的项目列表,然后使用 for 循环计算每个类别中的项目数。但是,我似乎无法弄清楚如何将数组与我的 DataProvider 数据项合并。

这是我目前的代码。

public function actionIndex()
{
    $dataProvider = new CActiveDataProvider('Category', array(
        'criteria' => array(
            'select' => 'id, name, slug',
            'order' => 'name ASC',
        ),
    ));
    $dataProvider->setPagination(false);
    $count = array();
    foreach($dataProvider->getData() as $categoryData) {
        $count[] = Item::model()->count("category_id = :categoryID", array("categoryID" => $categoryData->id));
    }
    $this->render('index', array(
        'dataProvider' => $dataProvider,
        'count' => $count,
    ));
}

如何将 $count 数组与我现有的 dataProvider 数据项合并,以便我可以将它与 CListView 一起使用?还有比这更好的解决方案吗?

【问题讨论】:

  • 如果您的关系设置正确,则不需要这样做。你能显示索引视图上的内容吗?
  • 其实如果你使用默认的gii创建的文件,你可以分享你的_view.php文件。

标签: php yii


【解决方案1】:

如果您的关系设置正确,则不需要单独的计数数组。您的index 视图很可能如下所示:

<h1>Messages</h1>
<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_view',
)); ?>

那么你的_view 应该是这样的:

<div class="view">
    <b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
    <?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
    <br />
    <b><?php echo CHtml::encode($data->getAttributeLabel('name')); ?>:</b>
    <?php echo CHtml::encode($data->name); ?>
    <br />
    <b>Items:</b>
    <?php echo count($data->items); ?>
    <br />
</div>

这是假设你的 Category 模型有这个:

public function relations() {
        return array(
            'items' => array(self::HAS_MANY, 'Item', 'category_id'),
        );
    }

【讨论】:

  • 嗨。感谢您的解决方案。我的关系已经定义好了,我只是在我的视图上应用了 count($data->items) 行。完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多