質問

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>
役に立ちましたか?

解決

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.

他のヒント

You don't need to use CActiveDataProvider, rather use the model directly.

Give it a try

foreach( User::model()->findAll() as $user ) {
   $address = $user->address;
   foreach( $address as $a ) {

   }
}

try using

$model= User::model()->with('address')->findAll();

Note:- address in with('address') is the relation Name.

Eg:- To get User records try this

foreach($model as $record)
{
echo $record->id . $record->name;
}

To get address records try this

foreach($model as $record)
    {
    foreach($record->address as $myaddress)
{
echo $myaddress->id . $myaddress->userId . $myaddress->address;
}
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top