How To Access A Related Tables Relations?

I have three mysql tables, collector, company, and reproduction. The reproduction table is related to the collector table through the foreign key of collectorID. The collector table is related to the company table through the foreign key companyID.

I need to access the company name for the collector from inside the Reproduction model. I can easily access the collector’s name from


$repro=Reproduction::model()->with('reproductionStatus','collector')->findAll('artID=:artID',array(':artID'=>$model->id));

using


foreach ($repro as record) echo $record->collector->name

How do I now carry the collector table’s relation over so I can access the company’s name from the company table?

Hi Joev you need can specify a through association take a look at this

http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through

Thanks. I’m not sure how to access the record. My model relations function now looks like


return array(

	'collector' => array(self::BELONGS_TO, 'Collector', 'collectorID'),

	'art' => array(self::BELONGS_TO, 'Art', 'artID'),

	'reproductionStatus' => array(self::BELONGS_TO, 'ReproductionStatus', 'reproductionStatusID'),

	'company'=>array(self::HAS_MANY,'Company',array('companyID'=>'id'),'through'=>'collector'),

);

and in my view file I have


$repro=Reproduction::model()->with('reproductionStatus','collector','company')->findAll('artID=:artID',array(':artID'=>$model->id));

foreach ($repro as $record)

	echo $record->collector->name.': '.$record->company->name.'<br />'; 

but I get a Trying to get property of non-object error.

What am I doing wrong?

You probably have the order wrong try this


<?php 


...

// this should be companies since you have has_many

'companies'=>[self::HAS_MANY, 'Company', ['companyID'=>'collectorID'], 'through'=>'collector']

...

The order was right but the relation was wrong. Each collector can only have one company (brain freeze moment) so I changed my relation to


//HAS_ONE not HAS_MANY

'company'=>array(self::HAS_ONE,'Company',array('companyID'=>'id'),'through'=>'collector'),

and it worked.

Thanks for all your help.