Yii 在listview中显示相关表列名
我有一个包含两个表的简单数据库:tbl_代码和tbl_用户Yii 在listview中显示相关表列名,yii,dataprovider,Yii,Dataprovider,我有一个包含两个表的简单数据库:tbl_代码和tbl_用户 **tbl_code** id(PK) accesscode createdby(FK references tbl_user.id) accesstime **tbl_user** id (PK) username password 我试图在listview中显示以下内容 id(待定代码.id) 存取码 createdby-(显示用户表中的用户名) 存取时间 电流控制器: $dataProvider=new CActiveDa
**tbl_code**
id(PK)
accesscode
createdby(FK references tbl_user.id)
accesstime
**tbl_user**
id (PK)
username
password
我试图在listview中显示以下内容
- id(待定代码.id)
- 存取码
- createdby-(显示用户表中的用户名)
- 存取时间
$dataProvider=new CActiveDataProvider('Code');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
索引视图
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
最后!
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('accesscode')); ?>:</b>
<?php echo CHtml::encode($data->accesscode); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('createdby')); ?>:</b>
<?php echo CHtml::encode($data->createdby); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('accesstime')); ?>:</b>
<?php echo CHtml::encode($data->accesstime); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('messagecount')); ?>:</b>
<?php echo CHtml::encode($data->messagecount); ?>
<br />
</div>
:
:
:
:
:
我应该在$dataprovider标准中连接这两个表,还是有更好的方法来实现这一点?
仍在与Yii打交道,任何帮助都将不胜感激 您可能会错过代码中的许多想法,因此我将展示一些您需要的东西: 在型号中 在模型中,需要指出存在的关系 在
User
中,您需要定义将此模型链接到代码的关系
public function relations(){
return array(
'codes'=>array(self::HAS_MANY, 'Code', 'createdby'),
);
}
在code
中
public function relations(){
return array(
'author'=>array(self::BELONGS_TO, 'User', 'createdby'),
);
}
现在,在控制器或视图中调用模型时,可以链接这些模型
数据提供者
在数据提供程序中,我们将指出加载代码时需要加载的相关模型:
$dataProvider=new CActiveDataProvider('Code', array(
'criteria'=>array(
'with'=>array('author'),
),
));
视图
现在,您可以在视图中显示作者:
<?php echo CHtml::encode($data->author->getAttributeLabel('username')); ?>:</b>
<?php echo CHtml::encode($data->author->username); ?>
:
对不起,我忘了提到我已经从gii工具生成了模型,代码模型上的关系()是:公共函数关系()
{返回数组(
'createdby'=>数组(self::属于,'TblUser','createdby'),
和关系()在用户模型上是:public function relations()
返回数组(
'tblCodes'=>数组(self::HAS_u MANY,'TblCode','createdby'),
);
,我注意到它指向了错误的文件名。i、 在我的例子中,TblUser是用户,TblCode是代码。但它成功了。谢谢