Getting data from related model

Hi,

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

id

maker_id

table: maintenance_event

id

plant_id --fk plant_attribute.id

table: service_schedule

id

maintenance_event_id – fk maintenance_event.id

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(

	'id'=>'service-schedule-grid',

	'dataProvider'=>$model->search(),

...


        'id',


        //  i can get the plant_id from maintenanceEvents using this

        'maintenanceEvent.plant_id'


        // 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




'maintenanceEvent.plantAttribute.maker_id'



if still no luck try this




  array(

    'name'=>'MakerId',

    'value'=>'$data->maintenanceEvent->plantAttribute->maker_id',

  ),



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/>';



/Tommy

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.

/Tommy

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.