Yii CGridview与关系模型


Yii CGridview with relational models

我在这里搜索了一个答案,但没有找到一个特定于我的问题的答案。

我相信我把模型之间的关系设置错了。。。我有一个使用模型的CGridView,其中一个字段是外部id,我想使用该外部id在模型中获取不同的字段。(例如,Question模型包含外键"tag1",我想使用"tag1"在表Tag中找到它的"name"字段)。

查看

    <?php
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$questions->search(),
    'filter' => $questions,
    'columns' => array(
        array('class'=>'CCheckBoxColumn'),
        'text',
        'tag1',
        array('header' => 'Tag 1', 'value' => '$questions->tag1->text'),
        'na',
        'cca',
    ),
));
?>

型号

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(
        'tag1' => array(self::HAS_ONE, 'Tags', 'id'),
    );
}

尝试给予此关系

 public function relations() {
        return array(
            'tags1'=>array(self::BELONGS_TO, 'Tags', 'id'),    
        );
    }

您只是弄错了变量,每一行都使用数据提供程序并存储在变量$data中,所以您只需要让它看起来像这样:

<?php
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$questions->search(),
    'filter' => $questions,
    'columns' => array(
        array('class'=>'CCheckBoxColumn'),
        'text',
        'tag1',
        array('header' => 'Tag 1', 'value' => '$data->tag1->text'),
        'tag1.text', //if you relation is setup correct you can also do this
        'na',
        'cca',
    ),
));
?>