0

我有一个带有 2 个表的简单数据库:tbl_code 和 tbl_user

**tbl_code**
id(PK)
accesscode
createdby(FK references tbl_user.id)
accesstime

**tbl_user**
id (PK)
username
password

我正在尝试在列表视图中显示以下内容

  • id (tbl_code.id)
  • 访问代码
  • createdby - (显示用户表中的用户名)
  • 访问时间

电流控制器:

$dataProvider=new CActiveDataProvider('Code');
    $this->render('index',array(
        'dataProvider'=>$dataProvider,
    ));

索引视图

<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_view',
)); ?>

最后是_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,任何帮助将不胜感激。

4

1 回答 1

0

您可能会在代码中错过很多想法,因此我将展示您需要的一些内容:

在模型中

在您的模型中,您需要指出存在的关系。

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'),
    ),
));

风景

现在在视图中 yiou 可以显示作者:

<?php echo CHtml::encode($data->author->getAttributeLabel('username')); ?>:</b>
<?php echo CHtml::encode($data->author->username); ?>
于 2013-04-04T11:58:33.967 回答