joev
(Reels)
March 10, 2014, 5:33pm
1
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?
alirz23
(Alirz23)
March 10, 2014, 6:03pm
2
joev
(Reels)
March 10, 2014, 10:31pm
3
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?
alirz23
(Alirz23)
March 11, 2014, 4:34am
4
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']
...
joev
(Reels)
March 11, 2014, 12:22pm
5
alirz23:
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.