Basically, I have two tables:
- jobs
+-------------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------+------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| site_id | int(10) | NO | | NULL | |
| name | varchar(255) | NO | | NULL | |
+-------------------------+------------------+------+-----+---------+----------------+
- sites
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| description | text | NO | | NULL | |
+------------------+------------------+------+-----+---------+----------------+
My model is setup with the following…
/**
* Model for Jobs
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'sites' => array(self::HAS_MANY, 'Sites', 'id'),
);
}
/**
* Model for Sites
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'jobs' => array(self::BELONGS_TO, 'Jobs', 'site_id'),
);
}
On the controller, I can do…
//$jobs = Jobs::model()->findAll();
$jobs = Jobs::model()->with('sites')->findAll();
And can access the attributes by…
foreach ($jobs as $key => $value) {
print_r($value->attributes);
}
The problem is, how to access the related sites?
Thanks for the help in advance, I been reading http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through. But, could not get it to work properly as it is saying I was missing an object?