Getting data from related model


I am not sure if I’m doing this right or if I should change my schema to make this work more effectively.

I have three tables:

table: plant_attribute



table: maintenance_event


plant_id --fk

table: service_schedule


maintenance_event_id – fk

and three models

Model: PlantAttribute

public function relations()


'maintenanceEvent' => array(self::HAS_MANY, 'MaintenanceEvent', 'plant_id'),


Model: MaintenanceEvent

public function relations()


'plantAttribute' => array(self::BELONGS_TO, 'PlantAttribute', 'plant_id'),

'serviceSchedule' => array(self::HAS_MANY, 'ServiceSchedule', 'maintenance_event_id'),


Model: ServiceSchedule

public function relations()


'maintenanceEvent' => array(self::BELONGS_TO, 'MaintenanceEvent', 'maintenance_event_id'),


I’m trying to retrieve maker_id from Model PlantAttribute in view ServiceSchedules/admin using CGridView

<?php $this->widget('zii.widgets.grid.CGridView', array(





        //  i can get the plant_id from maintenanceEvents using this


        // but how do i get maker_id from plantAttribute here?



Clearly I can’t do this, so will be creating a new column plant_id in table service_schedule and building my relations through it.

Thanks anyway.

IIRC I think you should be able to do this (but I’ll leave testing if it works to you).

You may have to add this to the search method (to perform eager loading)

  $criteria->with = array('maintenanceEvent', 'maintenanceEvent.plantAttribute');

  // $criteria->together = true;

Edit: fixed the with example (added array).

Try this syntax first


if still no luck try this





API Reference

If still no luck with CGridView, you should at least be able to see the result this way

  foreach ($model->search()->data as $m)

    echo 'Maker ID: '.$m->maintenanceEvent->plantAttribute->maker_id.'<br/>';


Found a reason to verify what I wrote. All my examples should work. Note: I added an array to the with example. But you should be able to use lazy loading, so no need to specify with at this time. Just use one of the two suggested CGridView syntaxes. Hint: keep it simple, don’t add a lot of features (such as search and sort) from start.


Thanks :)

I was looking for this and couldn’t find any examples in the forum. I’m sure I’m not the only one who had to do something similar.