Php 将数组与DataProvider数据项合并
我的Yii应用程序中有2个表类别和项目Php 将数组与DataProvider数据项合并,php,yii,Php,Yii,我的Yii应用程序中有2个表类别和项目 Category - id - name Item - id - category_id - name 我想做的是获得类别表中的项目列表,然后计算项目表中每个类别的项目数 我使用CActiveDataProvider检索类别表中的项目列表,然后使用for循环来计算每个类别中的项目数。但是,我似乎不知道如何将数组与我的DataProvider数据项合并 这是到目前为止我的代码 public function actionIndex() { $da
Category
- id
- name
Item
- id
- category_id
- name
我想做的是获得类别表中的项目列表,然后计算项目表中每个类别的项目数
我使用CActiveDataProvider检索类别表中的项目列表,然后使用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一起使用?有比这更好的解决方案吗?如果关系设置正确,就不需要单独的计数数组。您的
索引
视图很可能如下所示:
<h1>Messages</h1>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_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>
这是假设您的类别
模型具有以下特征:
public function relations() {
return array(
'items' => array(self::HAS_MANY, 'Item', 'category_id'),
);
}
如果关系设置正确,则不需要这样做。您可以显示索引视图上的内容吗?实际上,如果您使用的是默认的gii创建的文件,您可以共享您的
\u view.php
file.Hi。谢谢你的解决方案。我的关系已经定义,我只是在视图上应用了count($data->items)行。工作完美。