繁体   English   中英

具有HAS_MANY关系的Yii CGridView

[英]Yii CGridView with HAS_MANY relation

我在CGridView中显示HAS MANY关系时遇到了一些问题。

我想在CGridView中显示特定作者的所有文章标题,并用“,”(逗号)分隔。

这是一个简单的例子:

我有以下表格:

作者:id,name

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

在Author模型中,您可以编写一个函数,为您提供标题名称,

public function getAuthorsPostTitles()
{
    $text = 'no title yet';

    if(!empty($this->posts)) // if this Author has any related Posts
    {
        $counter = 0;
        foreach($this->posts as $post)
        {
            if($counter == 0) 
               $text = $post->title;
            else
               $text .= ', ' . $post->title;
        }
    }
    return $text;    
}

然后可以在网格中使用它:

array(
      'header'=>'Post Titles',
      'value'=> '$data->getAuthorsPostTitles()', 
),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM