phpyiicactiverecord

how can i get relation data by CActiverecord in yii?


I have 2 tables. tables have relation (HAS_MANY)
table1: user(id,name) table2:address(id,userId,address)
user can has some address I define relation in moles: user.php and address.php

user.php

 'address' => array(self::HAS_MANY, 'address', 'userId'),

address.php

'user' => array(self::BELONGS_TO, 'user', 'userId'),

when i write

$dataProvider = new CActiveDataProvider('user')

i get only record of user table but i want to get records two table i want to get name,array(address) For each user , how can do it?

UserController.php

public function actionIndex() {

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

index.php

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

_view.php

<b><?php echo $data->name)); ?>: <?php      $data->address->address;     ?>:</b>

Solution

  • In indexaction function, change the dataprovider code as below.

    $dataProvider = new CActiveDataProvider('User','criteria'=>array(
       'with'=>array(
           'address'
        ),
        'together'=>true,
    ));
    

    You can get the data from address table using $data->address->address_table_field_name in your view file.

    Here address is relation name defined in your user model file.