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'),
            );
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 使用 java+selenium 接管手动打开的IE浏览器
  • ¥15 ios 新安装app收不到fcm推送
  • ¥15 有没有实力的写手?有过成品的优先
  • ¥15 图像信息库的建立与识别
  • ¥15 韩国网站购物,KG支付的支付回调如何解决
  • ¥15 workstation导入ovf文件,报错,怎么解决呢?
  • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?