duancunsu9209 2013-08-07 17:49
浏览 96
已采纳

将数组与DataProvider数据项合并

I have 2 tables in my Yii application; Category and Item.

Category
- id
- name

Item
- id
- category_id
- name

What I would like to do is get a list of items in Category table and subsequently count the number of items of each category in the Item table.

I'm using CActiveDataProvider to retrieve a list of items in the the Category table and then subsequently use a for-loop to count the number of items in each category. However, I can't seem to figure out how to merge the array with my DataProvider data items.

Here is my code so far.

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,
    ));
}

How do I merge the $count array with my existing dataProvider data items so that I may use it with CListView? Is there a much more better solution than this?

  • 写回答

1条回答 默认 最新

  • doushi6947 2013-08-07 19:13
    关注

    You shouldn't need a seperate count array if your relationships are setup correctly. Most likely your index view looks like this:

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

    Then your _view should look like this:

    <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>
    

    This is assuming your Category model has this:

    public function relations() {
            return array(
                'items' => array(self::HAS_MANY, 'Item', 'category_id'),
            );
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵