使用CGridView显示另一个模型的属性

时间:2012-01-30 08:20:20

标签: php datagridview yii

我有这样的数据库

==== Group =====
id
name

==== Member ====
id
group_id
firstname
lastname

现在我可以使用multimodel在组控制器中使用成员成员的表属性。 由于我已经完成了多模型,因此我可以轻松地从单个视图页面对两个模型进行创建更新删除。现在我的问题是当我要在Group的管理视图文件中同时使用两个模型时,我必须在CGridView中显示这两个文件以在网格中显示。但我的问题是在CGridView中只能看到第一个模型。我希望第二个模型能够在CGridView上显示。那怎么办呢?

3 个答案:

答案 0 :(得分:4)

我认为您需要使用Relational Active Record组合模型。 在我正在学习的自学过程中,我希望我很快会有一个例子在这里发表...

编辑最后,我找到了一个例子。我(也许)在Yii中发现了一个错误,所以什么是一个简单的任务,需要的时间比必要的多...

我有两个型号,User e Persona,从gii获得,以前不相关。然后我将Persona添加到User作为可选属性:在User.php中

/**
 * @return array relational rules.
 */
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(
        'persona' => array(self::HAS_ONE,'Persona','id')
    );
}

然后,当绑定到CGridView时,User的模型会自动显示Persona中的选定字段:

<hr><?php
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => new CActiveDataProvider('User'),
    'columns' => array(
        'username',
        'password',
        'email',
        'persona.indirizzo'
        ),
    ));
?>

screen capture of instanced page

我发现的错误(可能需要调查更多):我的Persona模型的名称中有一个带有重音字符的属性,如果我使用它,我会收到一个错误:即如果

   'columns' => array(
        'username',
        'password',
        'email',
        'persona.identità'
        ),

然后页面无法实例化:

The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.

/home/carlo/public/yii-1.1.8.r3324/framework/zii/widgets/grid/CGridView.php(332)

320         foreach($this->columns as $column)
321             $column->init();
322     }
323 
324     /**
325      * Creates a {@link CDataColumn} based on a shortcut column specification string.
326      * @param string $text the column specification string
327      * @return CDataColumn the column instance
328      */
329     protected function createDataColumn($text)
330     {
331         if(!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/',$text,$matches))
332             throw new CException(Yii::t('zii','The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.'));
333         $column=new CDataColumn($this);
334         $column->name=$matches[1];

我认为这是不匹配的正则表达式......

答案 1 :(得分:0)

如果将groupId和groupName的getter添加到Member模型,则可以轻松显示成员的gridview并包含其组数据。这不是一个非常干净的解决方案,但它是最简单的。

答案 2 :(得分:0)

在组模型中定义一些类似'getGroupNameById'的函数,然后按如下方式调用它

$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,    //for members model
'columns'=>array(
    'id',          
    'firstName', 
    'lastName', 
    array(
        'name'=>'groupName'
        'value'=>'getGroupNameById($data->group_id)', 
        //$data is members row accessible in gridview
    ),
),
));

查看此帖子了解更多详情CGridView-Render-Customized-Complex-DataColumns

相关问题