【发布时间】:2014-06-12 03:15:37
【问题描述】:
我在 CGridView 中显示 HAS MANY 关系时遇到了一些问题。
我想在 CGridView 中显示特定作者的所有帖子标题,用“,”(逗号)分隔。
这是一个简单的例子:
我有以下表格:
作者:id、姓名
post:id,title,created(DATETIME),a_id.
帖子通过 a_id 属于作者。
型号:
public $postTitles;
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'posts' => array(self::HAS_MANY, 'Post', 'a_id'),
);
}
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->select="t.*,title AS postTitles";
$criteria->join="LEFT OUTER JOIN post on a_id=t.id";
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array("attributes"=>array(
'id',
'name',
)),
));
}
public function getPostTitles() {
$return = ',';
foreach ($this->posts as $post) {
$return .= $post->title;
}
return $return;
}
控制器:
public function actionIndex()
{
$model = new Author('search');
$this->render('index', array('model' => $model));
}
查看:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'author-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
array(
'id'=>'postTitles',
'type'=>'raw',
'value'=> array($model, 'getPostTitles'),
),
array(
'class'=>'CButtonColumn',
),
),
));
【问题讨论】: