2012-01-30 94 views
5

我有数据库,就像这个使用CGridView显示另一个模型的属性

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

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

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

回答

0

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

4

我认为你需要结合使用Relational Active Record模型。 在自我学习的过程,我下面,我希望不久将有一个例子,张贴在这里...

编辑最后,我制定了一个例子。我已经(也许)在Yii中发现了一个bug,所以什么是简单的任务,需要的时间超过了必要的时间......

我有两个模型,User e Persona,从gii获得,以前不相关。然后我人物角色添加到用户作为可选属性:

<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

:在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然后用户模型自动显示选择的字段

我发现的错误(可能需要调查更多):我的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]; 

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

+0

谢谢@chac您的答复。但第二个模型的属性不会在第一个模型的视图中加载。 – NewUser 2012-01-30 16:04:33

+0

indirizzo(最后一列)它在第二个模型中。我不明白你的评论... – CapelliC 2012-01-30 19:29:43

+0

雅我知道它从第二个模型,但如何从第二个模型获得indirizzo的价值? – NewUser 2012-01-31 03:07:36

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

相关问题