在Yii中,我正在做多模型。我的数据库有点像
+++++ Group ++++++
id
name
+++++ Member ++++++
id
group_id
firstname
lastname
membersince
在组控制器中,我想显示成员的属性。一切都很好,但当我使用菜单中的管理选项时,它会在两个不同的网格视图中显示两个模型的属性。会员控制器的代码如下
public function actionAdmin()
{
$model=new Group('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Group']))
{
$model->attributes=$_GET['Group'];
}
$member=new Member('search');
$member->unsetAttributes(); // clear any default values
if(isset($_GET['Member']))
{
$model->attributes=$_GET['Member'];
}
$this->render('admin',array(
'model'=>$model,
'member'=>$member,
));
}
对于在组中查看,管理代码如下
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'member-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
array(
'class'=>'CButtonColumn',
),
),
));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'member-grid',
'dataProvider'=>$member->search(),
'filter'=>$member,
'columns'=>array(
'firstname',
'lastname',
array(
'class'=>'CButtonColumn',
),
),
));
在这里,我已经使用CGridView两次来显示这两个属性的模型。有人能告诉我如何在一张单人床上展示模特吗CGridView。任何帮助和建议都将不胜感激。[更新]模型中的关系:组模型
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(
'member' => array(self::HAS_MANY, 'Member', 'group_id'),
);
}
会员模式:
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(
'group' => array(self::BELONGS_TO, 'Group', 'group_id'),
);
}
访问yii中相关模型字段的一种简单方法是使用类似的东西$model->relatedModel->field
——如果模型之间存在has_one或belongs_to关系,则可以使用此值
因此,在您的情况下,您可以使用代码
访问成员的组名$memberModel->group->name
但当您需要访问has_many或many_many关系类型的相关模型字段时,您将需要执行类似
的操作$model->relatedModel[arrayIndex]->field
这是因为在这种情况下有许多相关的模型,yii会自动为您提供数组中的相关模型
在您的情况下,组有许多成员,要访问组的特定成员(例如第一个成员,即arrayIndex=0),可以使用$groupModel->members[0]->firstname
现在来谈谈您的确切问题,首先,您不需要声明、初始化或传递$member模型。因此您的控制器操作可以是
public function actionAdmin(){
$model=new Group('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Group'])){
$model->attributes=$_GET['Group'];
}
$this->render('admin',array(
'model'=>$model
)
);
}
然后很明显,在你的视图中,你不需要两个网格视图
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'member-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
array( // this is for your related group members of the current group
'name'=>'members.firstname', // this will access the attributeLabel from the member model class, and assign it to your column header
'value'=>'$data->members[0]->firstname', // this will access the current group's 1st member and give out the firstname of that member
'type'=>'raw' // this tells that the value type is raw and no formatting is to be applied to it
),
array(
'class'=>'CButtonColumn',
),
),
));
希望这能有所帮助。