Get data from related tables in _view.php

Hi all,

I seem to be stuck here, would love some help.

I have this relations for the model:


return array(

			'categories'=>array(

			                self::MANY_MANY,

			                'Category',

			                'Bridge_category_item(category_id, item_id)'

			            ),

			            'Bridge_category_item'=>array(

			                self::HAS_MANY,

			                'BridgeCategoryItem',

			                'item_id'

			            ),

						'images' => array(

							self::HAS_MANY,

							'Images',

							'item_id'

							),

						'sale' => array(

							self::HAS_MANY,

							'Sale',

							'item_id'

							),

		);

I am trying to view this data in _view.php (index).

So now I have this CActiveDataProvider


$dataProvider=new CActiveDataProvider('Item',

		array(

              'criteria'=>array(

 		                    'with'=>array('Bridge_category_item','images','sale'),

 		                    'condition'=>'Bridge_category_item.category_id=2',

 		                //  'order'=>'t.id DESC',

 		                    'together'=>true,

 		                ),

		            )


		);

		

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

Now, if I print_r($data) in _view.php I can see that the other tables are there, but how do I access the data?

This does not not work:


$data->sale->duration

Thanks!

Been trying to figure this out for a while now… can anyone help please? No matter what I do I get an empty array for related models. Are those attributes need to be public?

Alright, I will answer myself.

Because its a HAS_MANY relationship, you have to go through an array to access the data.

So for sale:


$data->sale[id]->stock

For this to work, an index is needs to be define in the relationship:


						'sale' => array(

							self::HAS_MANY,

							'Sale',

							'item_id',

							'index' => 'item_id'

							),

		);

This way the index is the item_id column of the Sale table.

This helped:

http://tipstank.com/2010/06/14/get-related-object-by-primary-key-has_many-yii/