Search code examples
yiidataprovider

Displaying related table column name in listview


I have a simple database with 2 tables: tbl_code and tbl_user

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

**tbl_user**
id (PK)
username
password

I am trying to display the following in listview

  • id (tbl_code.id)
  • accesscode
  • createdby - (With this displaying the username from the user table)
  • accesstime

Current controller:

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

Index view

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

and finally _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>

Should I be joining these two tables in the $dataprovider criteria or is there a better way to achieve this? Still getting to grips with Yii, any help would be appreciated.


Solution

  • You could miss a lot of thinks in your code so I'll show some of the thing you'll need:

    In the models

    In your model you need to indicate the relation that exists.

    In User you need to define the relation that link this model to the code

    public function relations(){
        return array(
            'codes'=>array(self::HAS_MANY, 'Code', 'createdby'),
        );
    }
    

    And in Code you'll have

    public function relations(){
        return array(
            'author'=>array(self::BELONGS_TO, 'User', 'createdby'),
        );
    }
    

    Now the models can be linked when callign them in the controllers or the views

    The Data Provider

    In the data provider we will indicate the releted model that need to be loaded while loading code:

    $dataProvider=new CActiveDataProvider('Code', array(
        'criteria'=>array(
            'with'=>array('author'),
        ),
    ));
    

    The View

    Now in the view yiou can display the author:

    <?php echo CHtml::encode($data->author->getAttributeLabel('username')); ?>:</b>
    <?php echo CHtml::encode($data->author->username); ?>