HAS_MANY relation not returning any results

[color="#FF0000"]I solved this issue myself and it turned out to be based on a fault assumption. Please see my reply below and my edits in this post![/color]

OK, this has been driving me mad all day and I cannot work out what the problem is.

I have two tables:

Equipment

[color="#FF0000"]idequipment[/color]

equip_name

Changes

[color="#FF0000"]idchanges[/color]

change_date

change_details

[color="#00FF00"]idequipment[/color]

[color="#FF0000"]Primary Key[/color]

[color="#00FF00"]Foreign Key[/color]

Each row in Changes has one item of equipment that it relates to, using the foreign key idequipment.

Now, in Yii I can quite happily use the defined BELONGS_TO relation


'equipment' => array(self::BELONGS_TO, 'Equipment', 'idequipment')

to access all the equipment details relating to the Changes item. So I can view a Changes record in Yii and see any related Equipment information.

I have been asked to show a history of changes when viewing a piece of equipment. Naturally I assume I use the HAS_MANY relation in the Equipment model:


'changes' => array(self::HAS_MANY, 'Changes', 'idequipment'),

So in my View.php for Equipment I added:


'changes.change_date'

to the CDetailView widget.

I also edited the EquipmentController loadModel() method to add [font=“Courier New”]->with(‘changes’)[/font]


$model=Equipment::model()->with('changes')->findByPk($id);

Unfortunately, when I try going to the detailed view of an Equipment item all the fields from ‘changes’ are “Not Set”. If I try directly accessing [font=“Courier New”]$model->changes->‘afieldname’[/font] I get a ‘Trying to get property of non-object’ error.

[color="#FF0000"]The above should be [font=“Courier New”]$model->changes[0]->‘afieldname’[/font] since HAS_MANY returns an array, even with a single result.[/color]

All the records I am testing with are fully populated. The pieces of Equipment I am viewing are definitely linked to at least one Change record.

Any help would be greatly appreciated. Before I go bananas!

OK, I’m a muppet!

Everything was working perfectly, I just overlooked the fact when fetching relations via a HAS_MANY, the results are returned in an array.

It is starting to behave the way I expected now. Sorry if I wasted anyone’s time! :)

I think I have been staring at this code for far too long!